简体   繁体   English

标准事件如何在动态添加的元素上触发? (JQuery的)

[英]How can standard events fire on dynamically added elements? (JQuery)

I'm sorry for the poor wording on the title, if anybody can edit it to be more succinct and/or tell me what the proper terminology for what I'm looking for is, that would be great. 对于标题上的措词不好,我感到抱歉,如果有人可以对其进行编辑以使其更简洁和/或告诉我,我所寻找的正确术语是什么,那太好了。

With dynamically added elements typical event binding doesn't work, but people claim the following does: 使用动态添加的元素,典型的事件绑定不起作用,但是人们声称可以做到以下几点:

$('.elementClass').on('click',function() { });

I'm not having any luck with that, but of course this will always work: 我对此没有任何运气,但是当然这将一直有效:

$(document).on('click','.elementClass',function() { });

The problem is that will check the event every time the document is clicked, which obviously isn't very efficient. 问题在于,每次单击文档时都会检查事件,这显然不是很有效。 Is there a way of adding newly created elements into the flow so the following will still work on them? 有没有一种方法可以将新创建​​的元素添加到流中,因此下面的内容仍然适用于它们?

$('.elementClass').click(function() { });

Thanks in advance for any help you can offer, and perhaps for informing me of the proper vernacular! 在此先感谢您提供的任何帮助,并可能已将适当的本地语言告知我!

With dynamically added elements to bind events we have to use .on() . 通过动态添加元素来绑定事件,我们必须使用.on() Avoid excessive use of document or document.body for delegated events on large documents. 避免过多使用的documentdocument.body用于大型文档委派的事件。

Hierarchical selectors can often be avoided simply by attaching the handler to a more appropriate point in the document. 通常可以通过将处理程序附加到文档中更合适的点来避免层次选择器。 For example, instead of $(document).on('click','.elementClass',function() { }); 例如,代替$(document).on('click','.elementClass',function() { }); use $("#elementClass_parent_id").on('click','.elementClass',function() { });. 使用$("#elementClass_parent_id").on('click','.elementClass',function() { });.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM