jQuery .live() vs .on() 加载动态 html 后添加点击事件的方法 [英] jQuery .live() vs .on() method for adding a click event after loading dynamic html

查看:28
本文介绍了jQuery .live() vs .on() 加载动态 html 后添加点击事件的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 jQuery v.1.7.1,其中 .live() 方法显然已被弃用.

I am using jQuery v.1.7.1 where the .live() method is apparently deprecated.

我遇到的问题是,当使用以下方法将 html 动态加载到元素中时:

The problem I am having is that when dynamically loading html into an element using:

$('#parent').load("http://..."); 

如果我之后尝试添加点击事件,它不会使用以下任一方法注册该事件:

If I try and add a click event afterwards it does not register the event using either of these methods:

$('#parent').click(function() ...); 

// according to documentation this should be used instead of .live()
$('#child').on('click', function() ...); 

实现此功能的正确方法是什么?它似乎只适用于 .live() 对我来说,但我不应该使用这种方法.请注意,#child 是一个动态加载的元素.

What is the correct way to achieve this functionality? It only seems to work with .live() for me, but I shouldn't be using that method. Note that #child is a dynamically loaded element.

谢谢.

推荐答案

如果您希望点击处理程序为动态加载的元素工作,那么您可以在父对象上设置事件处理程序(不会动态加载) 并给它一个与您的动态对象相匹配的选择器,如下所示:

If you want the click handler to work for an element that gets loaded dynamically, then you set the event handler on a parent object (that does not get loaded dynamically) and give it a selector that matches your dynamic object like this:

$('#parent').on("click", "#child", function() {});

事件处理程序将附加到 #parent 对象,并且只要在 #child 上产生的点击事件冒泡到它,它就会触发您的点击处理程序.这称为委托事件处理(事件处理委托给父对象).

The event handler will be attached to the #parent object and anytime a click event bubbles up to it that originated on #child, it will fire your click handler. This is called delegated event handling (the event handling is delegated to a parent object).

这样做是因为您可以将事件附加到 #parent 对象,即使 #child 对象尚不存在,但当它稍后存在并获取时单击,单击事件将冒泡到 #parent 对象,它会看到它起源于 #child 并且有一个用于单击 的事件处理程序>#child 并触发您的事件.

It's done this way because you can attach the event to the #parent object even when the #child object does not exist yet, but when it later exists and gets clicked on, the click event will bubble up to the #parent object, it will see that it originated on #child and there is an event handler for a click on #child and fire your event.

这篇关于jQuery .live() vs .on() 加载动态 html 后添加点击事件的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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