jQuery .on函数用于将来的元素,因为不推荐使用.live [英] jQuery .on function for future elements, as .live is deprecated

查看:58
本文介绍了jQuery .on函数用于将来的元素,因为不推荐使用.live的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为将来的<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', ...)

http://api.jquery.com/live/

这篇关于jQuery .on函数用于将来的元素,因为不推荐使用.live的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆