jQuery .live()vs .on()方法在加载动态HTML后添加点击事件 [英] jQuery .live() vs .on() method for adding a click event after loading dynamic 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屋!