jQuery .on函数用于将来的元素,因为不推荐使用.live [英] jQuery .on function for future elements, as .live is deprecated
问题描述
我需要为将来的<div>
元素的click
事件添加一个处理程序,该事件尚不存在.通常,我会使用jQuery的.live
函数来处理此问题,但现在似乎已弃用它,而推荐使用.on
.
I need to add a handler for the click
event of future <div>
elements, that don't exist yet. Normally, I would use jQuery's .live
function to handle this, but it seems that it is now deprecated in favor of .on
.
要以这种方式使用.on
方法,jQuery建议设置选择器参数,以允许创建委托事件,并提供以下示例代码:
To use the .on
method in this manner, jQuery suggests setting the selector parameter, to allow creating a delegated event, and offers this example code:
$("#dataTable tbody").on("click", "tr", function(event){
alert($(this).text());
});
这一切都很好,但是我应该为我的初始选择器输入什么,因为他们有#dataTable tbody
?请注意,$.on()
不起作用.
That's all fine and good, but what do I put in for my intial selector, where they have #dataTable tbody
? Note that $.on()
doesn't work.
推荐答案
jQuery的文档显示您将替换
jQuery's documentation shows you would replace
$(selector).live(event, handler)
与
$(document).on(event, selector, handler)
此外,您还可以选择更精确的选项,并将$(document)
替换为元素的静态父级的选择器.例如,如果您有一个静态table
元素,并且tr
元素是动态添加到DOM的,则可以执行类似$('table#id').on('click', 'tr', ...)
Also you have the option to be more precise and replace $(document)
with a selector for a static parent of the element. For example, if you have a static table
element and tr
elements are added dynamically to the DOM, you could do something like $('table#id').on('click', 'tr', ...)
这篇关于jQuery .on函数用于将来的元素,因为不推荐使用.live的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!