如何在DOM更改后绑定到javascript事件?

时间:2022-11-26 23:55:02

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

我有一个函数可以绑定到tr标签来提供一个mouseover效果:

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

$("。网格tr”)。bind(“mouseenter”,function () {$(this).addClass(“hover”);})。绑定(“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?

问题是,当分页发生时,网格通过ajax加载,或者过滤等。这导致网格被完全替换,所有事件绑定都失败。是否有一种方法可以绑定到即使DOM发生变化时自动附加到匹配元素的事件?

Thanks!

谢谢!

3 个解决方案

#1


4  

$.live is what you want:

美元。生活就是你想要的:

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

#2


3  

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

从现在开始,请使用.on()。live()在jQuery中被弃用,因为它效率低下。

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

#3


0  

Alternatively, you could use $.delegate

或者,您可以使用$.delegate。

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

更多信息:在表的每一行上,将jQuery单击事件绑定到每个锚标记的最佳实践是什么。

#1


4  

$.live is what you want:

美元。生活就是你想要的:

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

#2


3  

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

从现在开始,请使用.on()。live()在jQuery中被弃用,因为它效率低下。

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

#3


0  

Alternatively, you could use $.delegate

或者,您可以使用$.delegate。

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

更多信息:在表的每一行上,将jQuery单击事件绑定到每个锚标记的最佳实践是什么。