jquery .live('click') 与 .click()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4944293/
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('click') vs .click()
提问by kalpaitch
I am wondering whether there are any circumstances where it would be better to use .click(function {...});
rather than .live('click', function {...});
?
我想知道是否有任何情况下使用.click(function {...});
而不是更好.live('click', function {...});
?
From what I gather the live option seems to be a better option and I am hence using it in almost all circumstances instead of the plain .click(), especially given a lot of my code is loaded asynchronously.
从我收集到的 live 选项似乎是一个更好的选择,因此我几乎在所有情况下都使用它而不是普通的 .click(),特别是考虑到我的很多代码是异步加载的。
EDIT: Another part to this question. If I'm asynchoronously loading all the javascript in, .click will still pickup all elements already in the dom. Right?
编辑:这个问题的另一部分。如果我异步加载所有 javascript, .click 仍将获取 dom 中已有的所有元素。对?
回答by Nathan MacInnes
There might be times when you explicitly want to only assign the click handler to objects which already exist, and handle new objects differently. But more commonly, live doesn't always work. It doesn't work with chained jQuery statements such as:
有时您可能明确只想将点击处理程序分配给已经存在的对象,并以不同的方式处理新对象。但更常见的是,live 并不总是有效。它不适用于链式 jQuery 语句,例如:
$(this).children().live('click',doSomething);
It needs a selector to work properly because of the way events bubble up the DOM tree.
由于事件在 DOM 树中冒泡的方式,它需要一个选择器才能正常工作。
Edit:Someone just upvoted this, so obviously people are still looking at it. I should point out that live
and bind
are both deprecated. You can perform both with .on()
, which IMO is a much clearer syntax. To replace bind
:
编辑:有人刚刚对此进行了投票,因此显然人们仍在关注它。我应该指出live
和bind
都已弃用。您可以同时使用.on()
,IMO 是一种更清晰的语法。替换bind
:
$(selector).on('click', function () {
...
});
and to replace live
:
并替换live
:
$(document).on('click', selector, function () {
...
});
Instead of using $(document)
, you can use any jQuery object which contains all the elements you're monitoring the clicks on, but the corresponding element must exist when you call it.
除了使用$(document)
,您还可以使用任何包含您正在监视点击的所有元素的 jQuery 对象,但是在调用它时相应的元素必须存在。
回答by T.J. Crowder
(Note 29/08/2017:live
was deprecated many versions ago and removed in v1.9. delegate
was deprecated in v3.0. In both cases, use the delegating signature of on
instead [also covered below].)
(注 29/08/2017:live
在许多版本之前delegate
已弃用,并在 v1.9 中删除。在 v3.0 中已弃用。在这两种情况下,请on
改用 [也在下文中介绍]的委托签名。)
live
happens by capturing the event when it's bubbled all the way up the DOM to the document root, and then looking at the source element. click
happens by capturing the event on the element itself. So if you're using live
, and one of the ancestor elements is hooking the event directly (and preventing it continuing to bubble), you'll never see the event on your element. Whereas normally, the element nearest the event (click or whatever) gets first grab at it, the mix of live
and non-live
events can change that in subtle ways.
live
当事件从 DOM 一直向上冒泡到文档根时捕获事件,然后查看源元素。click
通过在元素本身上捕获事件来发生。因此,如果您使用live
, 并且其中一个祖先元素直接挂钩事件(并防止其继续冒泡),您将永远不会在您的元素上看到该事件。而通常情况下,最接近事件(点击或其他)的元素会首先抓住它,live
而live
事件和非事件的混合可以以微妙的方式改变这一点。
For example:
例如:
jQuery(function($) {
$('span').live('click', function() {
display("<tt>live</tt> caught a click!");
});
$('#catcher').click(function() {
display("Catcher caught a click and prevented <tt>live</tt> from seeing it.");
return false;
});
function display(msg) {
$("<p>").html(msg).appendTo(document.body);
}
});
<div>
<span>Click me</span>
<span>or me</span>
<span>or me</span>
<div>
<span>I'm two levels in</span>
<span>so am I</span>
</div>
<div id='catcher'>
<span>I'm two levels in AND my parent interferes with <tt>live</tt></span>
<span>me too</span>
</div>
</div>
<!-- Using an old version because `live` was removed in v1.9 -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
I'd recommend using delegate
over live
when you can, so you can more thoroughly control the scope; with delegate
, you control the root element that captures the bubbling event (e.g., live
is basically delegate
using the document root as the root). Also, recommend avoiding (where possible) having delegate
or live
interacting with non-delegated, non-live event handling.
我建议您尽可能使用delegate
over live
,这样您就可以更彻底地控制范围;使用delegate
,您可以控制捕获冒泡事件的根元素(例如,live
基本上delegate
使用文档根作为根)。此外,建议避免(在可能的情况下)拥有非委托、非实时事件处理delegate
或live
与之交互。
Here several years later, you wouldn't use either live
or delegate
; you'd use the delegating signature of on
, but the concept is still the same: The event is hooked on the element you call on
on, but then fired only when descendants match the selector given after the event name:
几年后,您将不再使用live
or delegate
;您将使用 的委托签名on
,但概念仍然相同:该事件与您调用的元素挂钩on
,但仅当后代匹配事件名称后给出的选择器时才会触发:
jQuery(function($) {
$(document).on('click', 'span', function() {
display("<tt>live</tt> caught a click!");
});
$('#catcher').click(function() {
display("Catcher caught a click and prevented <tt>live</tt> from seeing it.");
return false;
});
function display(msg) {
$("<p>").html(msg).appendTo(document.body);
}
});
<div>
<span>Click me</span>
<span>or me</span>
<span>or me</span>
<div>
<span>I'm two levels in</span>
<span>so am I</span>
</div>
<div id='catcher'>
<span>I'm two levels in AND my parent interferes with <tt>live</tt></span>
<span>me too</span>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
回答by fmsf
All objects that would be associated with the .click must exist when you set the event.
设置事件时,所有与 .click 关联的对象都必须存在。
Example: (in pseudo code) the append can be $("body").append()
for example
示例:(在伪代码中)附加可以是$("body").append()
例如
append('<div id="foo" class="something">...</div>');
$("div.something").click(function(){...});
append('<div id="bar" class="something">...</div>');
Click works for foo but doesn't work for bar
单击适用于 foo 但不适用于 bar
Example2:
示例2:
append('<div id="foo" class="something">...</div>');
$("div.something").live("click",function(){...});
append('<div id="bar" class="something">...</div>');
click works for both foo and bar
click 对 foo 和 bar 都有效
With .live('click'... you can dynamicaly add more objects after you created the event and the clicking event will still work.
使用 .live('click'... 您可以在创建事件后动态添加更多对象,并且单击事件仍然有效。
回答by Mr. Black
"live" is needed when you dynamically generate code. Just look the below example :
动态生成代码时需要“live”。看看下面的例子:
$("#div1").find('button').click(function() {
$('<button />')
.text('BUTTON')
.appendTo('#div1')
})
$("#div2").find('button').live("click", function() {
$('<button />')
.text('BUTTON')
.appendTo('#div2')
})
button {
margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<div id="div1">
<button>Click</button>
</div>
<div id="div2">
<button>Live</button>
</div>
without "live" the click-event occurs only when you click the first button, with "live" the click-event occurs also for the dynamically generated buttons
没有“live”,点击事件仅在您单击第一个按钮时发生,“live”点击事件也会发生在动态生成的按钮上
回答by Felix Kling
Always use click
if you not dynamically add elements.
click
如果您不动态添加元素,请始终使用。
live
works by adding an event listener to the document root and listens for bubbled up events. An alternative is delegate
, which works the same, but binds the event handler to the specified element.
This way, the event has not to bubble up the whole DOM and is caught earlier.
live
通过将事件侦听器添加到文档根并侦听冒泡事件来工作。另一种方法是delegate
,它的工作原理相同,但将事件处理程序绑定到指定的元素。
这样,事件就不必冒泡整个 DOM 并更早地被捕获。
回答by dotty
.live() is used if elements are being added after the initial page load. Say you have a button which gets added by an AJAX call after the page gets loaded. This new button will not be accessible using .click(), so you'll have to use .live('click')
如果在初始页面加载后添加元素,则使用 .live() 。假设您有一个在页面加载后通过 AJAX 调用添加的按钮。使用 .click() 将无法访问此新按钮,因此您必须使用 .live('click')
回答by Lee Atkinson
As 'live' will handle events for future elements that match the current selector, you may choose click as you don't want that to happen - you only want to handle the current selected elements.
由于“live”将处理与当前选择器匹配的未来元素的事件,您可以选择单击,因为您不希望这种情况发生 - 您只想处理当前选定的元素。
Also, I suspect (though have no evidence) that there is a slight efficiency using 'click' over 'live'.
另外,我怀疑(尽管没有证据)使用“点击”而不是“实时”会有轻微的效率。
Lee
李
回答by Joe Green
From what I understand the key difference is that live() keeps an eye open for new DOM elements that match the selector you are working on, whereas click() (or bind('click')) attach the event hook and are finished.
据我了解,主要区别在于 live() 会留意与您正在处理的选择器匹配的新 DOM 元素,而 click()(或 bind('click'))附加事件挂钩并完成。
Given that alot of your code is loaded asynchronously, using live() will make your life alot easier. If you don't know exactly the code you are loading but you do know what kind of elements you will be listening to, then using this function makes perfect sense.
鉴于您的大量代码是异步加载的,使用 live() 将使您的生活更轻松。如果您不确切知道要加载的代码,但确实知道将要收听的元素类型,那么使用此功能就非常有意义。
In terms of performance gains, one alternative to using live() would be to implement an AJAX callback function to re-bind the event hooks.
就性能提升而言,使用 live() 的一种替代方法是实现 AJAX 回调函数以重新绑定事件挂钩。
var ajaxCallback = function(){
$('*').unbind('click');
$('.something').bind('click', someFunction);
$('.somethingElse').bind('click', someOtherFunction);
}
You will need to keep proper track of your event hooks and make sure this function is rebinding the proper events.
您需要正确跟踪事件挂钩并确保此函数重新绑定正确的事件。
p.s. Ajax methods .get(), .post(), .load() and .ajax() all let you specify a callback function.
ps Ajax 方法 .get()、.post()、.load() 和 .ajax() 都允许您指定回调函数。
回答by oryol
If you need simplify code then live is better in the most cases. If you need to get the best performance then delegate will always better than live. bind (click) vs delegate isn't so simple question (if you have a lot of similar items then delegate will be better).
如果您需要简化代码,那么在大多数情况下 live 会更好。如果您需要获得最佳性能,那么委托总是比现场更好。绑定(点击)vs 委托并不是那么简单的问题(如果你有很多类似的项目,那么委托会更好)。
回答by Fernando
remember that the use of "live" is for "jQuery 1.3" or higher
请记住,“live”的使用是针对“jQuery 1.3”或更高版本的
in version "jQuery 1.4.3" or higher is used "delegate"
在“jQuery 1.4.3”或更高版本中使用“委托”
and version "jQuery 1.7 +" or higher is used "on"
并且版本“jQuery 1.7 +”或更高版本用于“on”
$( selector ).live( events, data, handler ); // jQuery 1.3+
$( document ).delegate( selector, events, data, handler ); // jQuery 1.4.3+
$( document ).on( events, selector, data, handler ); // jQuery 1.7+
As of jQuery 1.7, the .live() method is deprecated.
从 jQuery 1.7 开始,不推荐使用 .live() 方法。
check http://api.jquery.com/live/
Regards, Fernando
问候, 费尔南多