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

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

问题描述

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





现在有什么选项?

div class =h2_lin>解决方案

  $(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天全站免登陆