Javascript jQuery .live() vs .on() 加载动态 html 后添加点击事件的方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8752321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery .live() vs .on() method for adding a click event after loading dynamic html
提问by Sean Thoman
I am using jQuery v.1.7.1 where the .live() method is apparently deprecated.
我正在使用 jQuery v.1.7.1,其中 .live() 方法显然已被弃用。
The problem I am having is that when dynamically loading html into an element using:
我遇到的问题是,当使用以下方法将 html 动态加载到元素中时:
$('#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() ...);
or
或者
// according to documentation this should be used instead of .live()
$('#child').on('click', function() ...);
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.
实现此功能的正确方法是什么?它似乎只适用于 .live() 对我来说,但我不应该使用这种方法。请注意,#child 是一个动态加载的元素。
Thanks.
谢谢。
回答by jfriend00
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() {});
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
,并且只要有一个点击事件冒泡到它,该事件起源于,它就会触发您的点击处理程序。这称为委托事件处理(事件处理委托给父对象)。
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.
它这样做的方式,因为你可以将事件附加到#parent
即使对象#child
对象还不存在,但是当后来存在并且被点击时,点击事件将泡沫达#parent
对象,它会发现它起源于#child
和有一个事件处理程序用于单击#child
并触发您的事件。
回答by Bojangles
Try this:
尝试这个:
$('#parent').on('click', '#child', function() {
// Code
});
From the $.on()
documentation:
从$.on()
文档:
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to
.on()
.
事件处理程序仅绑定到当前选定的元素;在您的代码调用 时,它们必须存在于页面上
.on()
。
Your #child
element doesn't exist when you call $.on()
on it, so the event isn't bound (unlike $.live()
). #parent
, however, doesexist, so binding the event to that is fine.
#child
当您调用$.on()
它时,您的元素不存在,因此事件未绑定(与 不同$.live()
)。#parent
但是,确实存在,因此将事件绑定到该事件是可以的。
The second argument in my code above acts as a 'filter' to only trigger if the event bubbled up to #parent
from #child
.
我上面代码中的第二个参数充当“过滤器”,仅在事件冒泡到#parent
from时才触发#child
。
回答by L422Y
$(document).on('click', '.selector', function() { /* do stuff */ });
$(document).on('click', '.selector', function() { /* do stuff */ });
EDIT: I'm providing a bit more information on how this works, because... words. With this example, you are placing a listener on the entire document.
编辑:我提供了更多关于它是如何工作的信息,因为......词。在此示例中,您将在整个文档上放置一个侦听器。
When you click
on any element(s) matching .selector
, the event bubbles up to the main document -- so long as there's no other listeners that call event.stopPropagation()
method -- which would top the bubbling of an event to parent elements.
当您click
使用任何匹配的元素时.selector
,事件会冒泡到主文档——只要没有其他调用event.stopPropagation()
方法的侦听器——这将超过事件到父元素的冒泡。
Instead of binding to a specific element or set of elements, you are listening for any events coming from elements that match the specified selector. This means you can create one listener, one time, that will automatically match currently existing elements as well as any dynamically added elements.
您不是绑定到特定元素或元素集,而是侦听来自与指定选择器匹配的元素的任何事件。这意味着您可以一次性创建一个侦听器,该侦听器将自动匹配当前存在的元素以及任何动态添加的元素。
This is smart for a few reasons, including performance and memory utilization (in large scale applications)
这很聪明,原因有几个,包括性能和内存利用率(在大型应用程序中)
EDIT:
编辑:
Obviously, the closest parent element you can listen on is better, and you can use any element in place of document
as long as the children you want to monitor events for are within that parent element... but that really does not have anything to do with the question.
显然,您可以侦听的最接近的父元素更好,并且您可以使用任何元素来代替,document
只要您要监视事件的子元素在该父元素内……但这实际上没有任何关系带着问题。
回答by Jared
The equivalent of .live() in 1.7 looks like this:
1.7 中 .live() 的等价物如下所示:
$(document).on('click', '#child', function() ...);
Basically, watch the document for click events and filter them for #child.
基本上,查看文档中的点击事件并为#child 过滤它们。
回答by NSV
I know it's a little late for an answer, but I've created a polyfill for the .live() method. I've tested it in jQuery 1.11, and it seems to work pretty well. I know that we're supposed to implement the .on() method wherever possible, but in big projects, where it's not possible to convert all .live() calls to the equivalent .on() calls for whatever reason, the following might work:
我知道答案有点晚了,但我已经为 .live() 方法创建了一个 polyfill。我已经在 jQuery 1.11 中测试过它,它似乎工作得很好。我知道我们应该尽可能地实现 .on() 方法,但在大型项目中,无论出于何种原因都无法将所有 .live() 调用转换为等效的 .on() 调用,以下可能工作:
if(jQuery && !jQuery.fn.live) {
jQuery.fn.live = function(evt, func) {
$('body').on(evt, this.selector, func);
}
}
Just include it after you load jQuery and before you call live().
只需在加载 jQuery 之后和调用 live() 之前包含它。
回答by Matt Cashatt
.on() is for jQuery version 1.7 and above. If you have an older version, use this:
.on() 适用于 jQuery 1.7 及更高版本。如果您有旧版本,请使用以下命令:
$("#SomeId").live("click",function(){
//do stuff;
});
回答by Coderx07
I used 'live' in my project but one of my friend suggested that i should use 'on' instead of live. And when i tried to use that i experienced a problem like you had.
我在我的项目中使用了“live”,但我的一位朋友建议我应该使用“on”而不是 live。当我尝试使用它时,我遇到了像您一样的问题。
On my pages i create buttons table rows and many dom stuff dynamically. but when i use on the magic disappeared.
在我的页面上,我动态创建按钮表行和许多 dom 内容。但是当我用上魔法就消失了。
The other solutions like use it like a child just calls your functions every time on every click. But i find a way to make it happen again and here is the solution.
其他解决方案就像孩子一样使用它,每次点击时都会调用您的函数。但我找到了一种方法让它再次发生,这是解决方案。
Write your code as:
将您的代码编写为:
function caller(){
$('.ObjectYouWntToCall').on("click", function() {...magic...});
}
Call caller(); after you create your object in the page like this.
调用调用者(); 在像这样在页面中创建对象之后。
$('<dom class="ObjectYouWntToCall">bla... bla...<dom>').appendTo("#whereeveryouwant");
caller();
By this way your function is called when it is supposed to not every click on the page.
通过这种方式,您的函数在不应该每次点击页面时都会被调用。