开发者

How to bind to javascript events after the DOM changes

开发者 https://www.devze.com 2022-12-29 15:33 出处:网络
I have a function that binds to a tr tag to provide a mouseover effect like this: $(\".grid tr\").bind(\"mouseenter\",

I have a function that binds to a tr tag to provide a mouseover effect like this:

$(".grid tr").bind("mouseenter", function () { $(this).addClass("hover"); }).bind("mouseleave", function () 开发者_开发知识库{ $(this).removeClass("hover"); });

The problem is the grid is loaded via ajax when paging occurs, or filtering etc. This causes the grid to be completely replaced and all the event bindings to fail. Is there a way to bind to an event that automatically attaches to matching elements even when the DOM changes?

Thanks!


$.live is what you want:

$(".grid tr").live("mouseenter", function () { $(this).addClass("hover"); }).bind("mouseleave", function () { $(this).removeClass("hover"); });


Please use .on() from now on, as .live() is deprecated in jQuery as it is inefficient.

$(".grid tr")
    .on("mouseenter", function () { $(this).addClass("hover"); })
    .on("mouseleave", function () { $(this).removeClass("hover"); });


Alternatively, you could use $.delegate

More info: what is the best practice of binding jQuery click event to each anchor tag on every row of a table

0

精彩评论

暂无评论...
验证码 换一张
取 消