动态添加到DOM的元素的点击事件 [英] Click event for elements added to DOM dynamically

查看:146
本文介绍了动态添加到DOM的元素的点击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在jQuery 1.8之前,当jquery动态插入按钮被点击时,我可以使用.live()来触发。



现在,.on()和.bind()两者都不适用于在页面加载后添加到DOM的元素。



现在有什么选择?

解决方案

  $(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.

这篇关于动态添加到DOM的元素的点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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