Javascript 为什么使用 jQuery on() 而不是 click()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10082031/
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
Why use jQuery on() instead of click()
提问by JasonDavis
Currently with jQuery when I need to do something when a Click occurs I will do it like this...
目前使用 jQuery,当我需要在发生 Click 时做某事时,我会这样做...
$(".close-box").click( function() {
MoneyBox.closeBox();
return false;
});
I was looking at some code someone else has on a project and they do it like this...
我正在查看其他人在项目中的一些代码,他们这样做...
$(".close-box").live("click", function () {
MoneyBox.closeBox();
return false;
});
Notice it seems to do the same thing as far as I can tell except they are using the live() function which is now Deprecated and jQuery docs say to use on()
instead but either way why use live/on() instead of my first example?
请注意,据我所知,它似乎在做同样的事情,除了他们使用的是 live() 函数,该函数现在已被弃用,jQuery 文档说要使用它,on()
但无论哪种方式,为什么使用 live/on() 而不是我的第一个例子?
回答by Andreas Wong
Because you might have a dynamically generated elements (for example coming from an AJAX call), you might want to have the same click handler that was previously bound to the same element selector, you then "delegate" the click event using on()
with selector argument
因为您可能有一个动态生成的元素(例如来自 AJAX 调用),您可能希望拥有之前绑定到同一个元素选择器的相同点击处理程序,然后您使用on()
with selector 参数“委托”点击事件
To demonstrate:
展示:
on()
can also be synonymous with click()
if you don't have a selector specified:
on()
click()
如果您没有指定选择器,也可以是同义词:
$('.elementClass').click(function() { // code
});
is synonymous with
是同义词
$('.elementClass').on('click', function() { // code
});
In the sense that it only add the handler one time to all elements with class elementClass
. If you have a new elementClass
coming from, for example $('<div class="elementClass" />')
, the handler won't be bound on that new element, you need to do:
从某种意义上说,它只向所有具有 class 的元素添加处理程序一次elementClass
。elementClass
例如$('<div class="elementClass" />')
,如果您有一个新元素,则处理程序不会绑定到该新元素上,您需要执行以下操作:
$('#container').on('click', '.elementClass', function() { // code
});
Assuming #container
is .elementClass
's ancestor
假设#container
是.elementClass
的祖先
回答by Eli Sand
There are a lot of answers, each touching on a few points - hopefully this can give you your answer, with a good explanation of what's what and how to use it.
有很多答案,每个都涉及几个要点 - 希望这可以为您提供答案,并很好地解释了什么是什么以及如何使用它。
Using click()
is an alias to bind('click' ...)
. Using bind()
takes the DOM as it is when the event listener is being set up and binds the function to each of the matching elements in the DOM. That is to say if you use $('a').click(...)
you will bind the function supplied to the click event of every anchor tag in the DOM found when that code runs.
Usingclick()
是 的别名bind('click' ...)
。Usingbind()
在设置事件侦听器时使用DOM,并将函数绑定到 DOM 中的每个匹配元素。也就是说,如果您使用,$('a').click(...)
您将绑定提供给该代码运行时在 DOM 中找到的每个锚标记的单击事件的函数。
Using live()
was the old way in jQuery; it was used to bind events just like bind()
does, but it doesn't just bind them to elements in the DOM when the code runs - it also listens to changes in the DOM and will bind events to any future-matched elements as well. This is useful if you're doing DOM manipulation and you need an event to exist on some elements that may get removed/updated/added to the DOM later but don't exist when the DOM is first loaded.
使用live()
是 jQuery 中的旧方法;它被用来绑定事件,就像bind()
它一样,但它不只是在代码运行时将它们绑定到 DOM 中的元素——它还侦听 DOM 中的变化,并将事件绑定到任何未来匹配的元素。如果您正在执行 DOM 操作,并且您需要在某些元素上存在一个事件,这些元素稍后可能会被删除/更新/添加到 DOM 但在首次加载 DOM 时不存在,则这很有用。
The reason that live()
is now depreciated is because it was poorly implemented. In order to use live()
, you had to be able to select at least one element in the DOM initially (I believe). It also caused a copy of the function to run to be bound to each element - and if you have 1000 elements, that's a lot of copied functions.
live()
现在贬值的原因是因为它执行不力。为了使用live()
,您必须能够在最初的 DOM 中至少选择一个元素(我相信)。它还导致运行的函数副本绑定到每个元素 - 如果您有 1000 个元素,那就是很多复制的函数。
The creation of the on()
function was to overcome those problems. It lets you bind a single event listener to an object that will not change in the DOM (so you can't use on()
on an element that will be removed/added to the DOM later - bind it to a parent object), and simply apply an element "filter" so that the function is only run when it is bubbled up to an element that matches the selector. This means you have just one function that exists (not a bunch of copies) bound to a single element - a much better approach to adding "live" events in the DOM.
该on()
功能的创建就是为了克服这些问题。它允许您将单个事件侦听器绑定到不会在 DOM 中更改的对象(因此您不能on()
在稍后将删除/添加到 DOM 的元素上使用- 将其绑定到父对象),然后简单地应用一个元素“过滤器”,以便该函数仅在冒泡到与选择器匹配的元素时才运行。这意味着您只有一个绑定到单个元素的函数(不是一堆副本)——这是在 DOM 中添加“实时”事件的更好方法。
... and that is what the differences are, and why each function exists and why live()
is depreciated.
...这就是差异所在,以及每个功能存在的原因以及live()
折旧的原因。
回答by u283863
$("a").live()
--> It will apply to all<a>
, even if it is created after this is called.$("a").click()
--> It will only apply to all<a>
before this is called. (This is a shortcut ofbind()
, andon()
in 1.7)$("a").on()
--> Provides all functionality required for attaching event handlers. (Newest in jQuery 1.7)
$("a").live()
--> 它将适用于 all<a>
,即使它是在调用 this 之后创建的。$("a").click()
--> 它只适用于<a>
调用此之前的所有内容。(这是bind()
, 和on()
1.7 中的快捷方式)$("a").on()
--> 提供附加事件处理程序所需的所有功能。(jQuery 1.7 中的最新版本)
行情:
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().
This method provides a means to attach delegated event handlers to the document element of a page, which simplifies the use of event handlers when content is dynamically added to a page. See the discussion of direct versus delegated events in the .on() method for more information.
从 jQuery 1.7 开始,不推荐使用 .live() 方法。使用 .on() 附加事件处理程序。旧版本 jQuery 的用户应该优先使用 .delegate() 而不是 .live()。
此方法提供了一种将委托的事件处理程序附加到页面的文档元素的方法,这在将内容动态添加到页面时简化了事件处理程序的使用。有关更多信息,请参阅 .on() 方法中直接事件与委托事件的讨论。
The .on() method attaches event handlers to the currently selected set of elements in the jQuery object. As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers.
.on() 方法将事件处理程序附加到 jQuery 对象中当前选定的一组元素。从 jQuery 1.7 开始, .on() 方法提供了附加事件处理程序所需的所有功能。
For earlier versions, the .bind() method is used for attaching an event handler directly to elements.
对于早期版本, .bind() 方法用于将事件处理程序直接附加到元素。
回答by elclanrs
click()
is a shortcut to the non delegation method of on()
. So:
click()
是 的非委托方法的快捷方式on()
。所以:
$(".close-box").click() === $(".close-box").on('click')
To delegate events with on()
, ie. in dynamic created objects you can do:
用 委托事件on()
,即。在动态创建的对象中,您可以执行以下操作:
$(document).on('click', '.close-box') // Same as $('.close-box').live()
But, on()
introduces delegation in any static element, not just document
as live()
does, so:
但是,on()
在任何静态元素中引入委托,而不只是document
像live()
那样,所以:
$("#closestStaticElement").on('click', '.close-box')
回答by josh3736
You should read up on the difference between live
and bind
.
您应该仔细阅读和之间的区别live
bind
。
In a nutshell, live
uses event delegation, allowing you to bind to elements that exist now and in the future.
简而言之,live
使用事件委托,允许您绑定到现在和将来存在的元素。
In contrast, handlers attached via bind
(and its shortcuts, like click
) attach handlers directlyto the DOM elements matching the selector, and therefore are only bound to elements that exist now.
相比之下,通过bind
(及其快捷方式,如click
)附加的处理程序将处理程序直接附加到与选择器匹配的 DOM 元素,因此只绑定到现在存在的元素。
A consequence of live
's flexibility is decreased performance, so only use it when you need the functionality it provides.
的后果live
的灵活性,性能降低,所以只有当你需要它提供的功能使用。
回答by Casey Foster
$el.click(fn)
is a shortcut for $el.on('click', fn)
$el.click(fn)
是捷径 $el.on('click', fn)
See http://api.jquery.com/click/and http://api.jquery.com/on/for more info.
有关更多信息,请参阅http://api.jquery.com/click/和http://api.jquery.com/on/。
回答by The Alpha
When you need to bind some event handlers to dynamically added elements
you have to use live
(deprecated) or on
make the it working. Simply $('element').click(...);
won't work on any dynamically added element in to the DOM.
当您需要绑定一些事件处理程序时,dynamically added elements
您必须使用live
(已弃用)或on
使其工作。根本$('element').click(...);
不会处理任何动态添加到 DOM 的元素。
More on The Difference Between jQuery's .bind(), .live(), and .delegate().
回答by ZeroSkittles
The .on()
method attaches event handlers to the currently selected set of elements in the jQuery object. The click()
method binds an event handler to the "click" JavaScript event, or triggers that event on an element.
该.on()
方法将事件处理程序附加到 jQuery 对象中当前选定的一组元素。该click()
方法将事件处理程序绑定到“click”JavaScript 事件,或在元素上触发该事件。
In the plain .click(...
if the target of the selector changes on the fly (e.g via some ajax response) then you'd need to assign the behavior again.
在普通情况下,.click(...
如果选择器的目标动态更改(例如,通过一些 ajax 响应),那么您需要再次分配行为。
The .on(...
is very new (jQuery 1.7) and it can cover the live scenario using delegated events which is a faster way to attach behavior anyway.
这.on(...
是非常新的(jQuery 1.7),它可以使用委托事件覆盖实时场景,无论如何这是附加行为的更快方法。
回答by Checksum
$.click() is merely a shortcut for either bind or on. From jQuery docs:
$.click() 只是 bind 或 on 的快捷方式。来自 jQuery 文档:
In the first two variations, this method is a shortcut for .bind("click", handler), as well as for .on("click", handler) as of jQuery 1.7. In the third variation, when .click() is called without arguments, it is a shortcut for .trigger("click").
在前两个变体中,此方法是 .bind("click", handler) 的快捷方式,自 jQuery 1.7 起也是 .on("click", handler) 的快捷方式。在第三种变体中,当不带参数调用 .click() 时,它是 .trigger("click") 的快捷方式。
回答by Sushil Kumar
In on
method, event handler is attached to the parent element instead of target.
在on
方法中,事件处理程序附加到父元素而不是目标。
example: $(document).on("click", ".className", function(){});
例子: $(document).on("click", ".className", function(){});
In above example, click event handler is attached to document. And it uses event bubbling to know whether someone clicked on the target element.
在上面的示例中,单击事件处理程序附加到文档。它使用事件冒泡来知道是否有人点击了目标元素。