且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

动态添加到DOM的元素的点击事件

更新时间:2023-11-03 14:44:16

  $(parent_element).on(click,child_selector,function(evt){
});

http://api.jquery.com/on/#direct-and-delegated-events


委托事件的优点在于,它们可以处理后来添加到文档中的后代元素的事件。通过选择在委托事件处理程序附加时保证存在的元素,可以使用委托事件来避免经常附加和删除事件处理程序。该元素可以是Model-View-Controller设计中的视图的容器元素,例如,如果事件处理程序想监视文档中的所有冒泡事件,则可以是document。文件元素在加载任何其他HTML之前可以在文档的头部使用,因此可以安全地在那里附加事件,而无需等待文档准备就绪。



Before jQuery 1.8 I was able to use .live() to fire when a button was clicked that was dynamically inserted by jquery.

Now, .on() and .bind() both do not work for elements added to DOM after the page was loaded.

What are the options now?

$(parent_element).on("click", child_selector, function(evt) {
});

http://api.jquery.com/on/#direct-and-delegated-events

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.