jQuery .on 函数用于未来元素,因为 .live 已弃用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8191064/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:11:58  来源:igfitidea点击:

jQuery .on function for future elements, as .live is deprecated

jquery

提问by Brad

I need to add a handler for the clickevent of future <div>elements, that don't exist yet. Normally, I would use jQuery's .livefunction to handle this, but it seems that it is now deprecated in favor of .on.

我需要为尚不存在click的未来<div>元素的事件添加一个处理程序。通常,我会使用 jQuery 的.live函数来处理这个问题,但现在似乎不赞成使用.on.

To use the .onmethod in this manner, jQuery suggests setting the selector parameter, to allow creating a delegated event, and offers this example code:

.on以这种方式使用该方法,jQuery 建议设置选择器参数,以允许创建委托事件,并提供以下示例代码:

$("#dataTable tbody").on("click", "tr", function(event){
    alert($(this).text());
});

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.

这一切都很好,但是我应该为我的初始选择器放入什么,它们在#dataTable tbody哪里?请注意,$.on()这不起作用。

回答by wrschneider

jQuery's documentation shows you would replace

jQuery 的文档显示您将替换

$(selector).live(event, handler) 

with

$(document).on(event, selector, handler)

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 tableelement and trelements are added dynamically to the DOM, you could do something like $('table#id').on('click', 'tr', ...)

您还可以选择更精确并替换$(document)为元素的静态父级的选择器。例如,如果您有一个静态table元素并且tr元素被动态添加到 DOM,您可以执行以下操作$('table#id').on('click', 'tr', ...)

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

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

回答by Brad

I just figured it out as soon as I posted this question... Sorry about that!

我刚发布这个问题就想通了……对不起!

The initial selector can be any parent element. Since my elements will be direct children of the body, I can use bodyfor the selector:

初始选择器可以是任何父元素。由于我的元素将是 body 的直接子元素,因此我可以将其body用于选择器:

$('body').on('click', '.my_class', function(event) { ...

This works because the events are going to bubble up. This is essentially normal bubbling with an extra filter of .my_class.

这是有效的,因为事件会冒泡。这本质上是带有额外过滤器的正常冒泡.my_class