jQuery .on('click') 与 .click() 的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9122078/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:22:26  来源:igfitidea点击:

Difference between .on('click') vs .click()

jqueryclick

提问by bgcode

Is there any difference between the following code?

下面的代码有什么区别吗?

$('#whatever').on('click', function() {
     /* your code here */
});

and

$('#whatever').click(function() {
     /* your code here */
});

回答by andreister

I think, the difference is in usage patterns.

我认为,区别在于使用模式。

I would prefer .onover .clickbecause the former canuse less memory and work for dynamically added elements.

我更喜欢前者.on.click因为前者可以使用更少的内存并为动态添加的元素工作。

Consider the following html:

考虑以下 html:

<html>
    <button id="add">Add new</button>
    <div id="container">
        <button class="alert">alert!</button>
    </div>
</html>

where we add new buttons via

我们通过添加新按钮的地方

$("button#add").click(function() {
    var html = "<button class='alert'>Alert!</button>";
    $("button.alert:last").parent().append(html);
});

and want "Alert!" to show an alert. We can use either "click" or "on" for that.

并想要“警报!” 显示警报。为此,我们可以使用“click”或“on”。



When we use click

当我们使用 click

$("button.alert").click(function() {
    alert(1);
});

with the above, a separatehandler gets created for every single elementthat matches the selector. That means

有了上面的内容,为每个与选择器匹配的元素创建了一个单独的处理程序。这意味着

  1. many matching elements would create many identical handlers and thus increase memory footprint
  2. dynamically added items won't have the handler - ie, in the above html the newly added "Alert!" buttons won't work unless you rebind the handler.
  1. 许多匹配的元素会创建许多相同的处理程序,从而增加内存占用
  2. 动态添加的项目不会有处理程序 - 即,在上面的 html 中新添加的“警报!” 除非您重新绑定处理程序,否则按钮将不起作用。

When we use .on

当我们使用 .on

$("div#container").on('click', 'button.alert', function() {
    alert(1);
});

with the above, a singlehandler for all elementsthat match your selector, including the ones created dynamically.

与上面,一个单一的处理程序的所有元素的选择相匹配的,其中包括动态创建的。



...another reason to use .on

...使用的另一个原因 .on

As Adrien commented below, another reason to use .onis namespaced events.

正如 Adrien 在下面评论的那样,另一个使用的原因.on是命名空间事件。

If you add a handler with .on("click", handler)you normally remove it with .off("click", handler)which will remove that very handler. Obviously this works only if you have a reference to the function, so what if you don't ? You use namespaces:

如果你添加一个处理程序,.on("click", handler)你通常会删除它,.off("click", handler)这将删除那个处理程序。显然,这只有在您有对该函数的引用时才有效,如果没有呢?您使用命名空间:

$("#element").on("click.someNamespace", function() { console.log("anonymous!"); });

with unbinding via

通过解除绑定

$("#element").off("click.someNamespace");

回答by gilly3

Is there any difference between the following code?

下面的代码有什么区别吗?

No, there is no functional difference between the two code samples in your question. .click(fn)is a "shortcut method" for .on("click", fn). From the documentation for .on():

不,您问题中的两个代码示例之间没有功能差异。 .click(fn)是 的“快捷方式” .on("click", fn)。从文档中.on()

There are shorthand methods for some events such as .click()that can be used to attach or trigger event handlers. For a complete list of shorthand methods, see the events category.

某些事件有一些速记方法,例如.click()可用于附加或触发事件处理程序的方法。有关速记方法的完整列表,请参阅事件类别

Note that .on()differs from .click()in that it has the ability to create delegated event handlersby passing a selectorparameter, whereas .click()does not. When .on()is called without a selectorparameter, it behaves exactly the same as .click(). If you want event delegation, use .on().

请注意,它的.on()不同之处.click()在于它能够通过传递参数来创建委托的事件处理程序selector,而.click()不能。在.on()不带selector参数的情况下调用时,它的行为与.click(). 如果您想要事件委托,请使用.on().

回答by Interrobang

.on()is the recommended way to do all your event binding as of jQuery 1.7. It rolls all the functionality of both .bind()and .live()into one function that alters behavior as you pass it different parameters.

.on()是从 jQuery 1.7 开始执行所有事件绑定的推荐方法。这两个卷的所有功能.bind(),并.live()成一个功能,当您将它传递不同的参数会改变行为。

As you have written your example, there is no difference between the two. Both bind a handler to the clickevent of #whatever. on()offers additional flexibility in allowing you to delegate events fired by children of #whateverto a single handler function, if you choose.

正如您编写的示例一样,两者之间没有区别。两者都将处理程序绑定到 的click事件#whateveron()提供额外的灵活性,允许您将子代触发的事件委托#whatever给单个处理程序函数,如果您愿意的话。

// Bind to all links inside #whatever, even new ones created later.
$('#whatever').on('click', 'a', function() { ... });

回答by nnnnnn

As mentioned by the other answers:

正如其他答案所提到的:

$("#whatever").click(function(){ });
// is just a shortcut for
$("#whatever").on("click", function(){ })

Noting though that .on()supports several other parameter combinations that .click()doesn't, allowing it to handle event delegation (superceding .delegate()and .live()).

请注意,虽然它.on()支持其他几个.click()不支持的参数组合,但允许它处理事件委托(取代.delegate().live())。

(And obviously there are other similar shortcut methods for "keyup", "focus", etc.)

(显然还有其他类似的“keyup”、“focus”等快捷方式)

The reason I'm posting an extra answer is to mention what happens if you call .click()with no parameters:

我发布额外答案的原因是提到如果您.click()不带参数调用会发生什么:

$("#whatever").click();
// is a shortcut for
$("#whatever").trigger("click");

Noting that if you use .trigger()directly you can also pass extra parameters or a jQuery event object, which you can't do with .click().

请注意,如果您.trigger()直接使用,您还可以传递额外的参数或 jQuery 事件对象,而使用.click().

I also wanted to mention that if you look at the jQuery source code (in jquery-1.7.1.js) you'll see that internally the .click()(or .keyup(), etc.) function will actually call .on()or .trigger(). Obviously this means you can be assured that they really do have the same result, but it also means that using .click()has a tiny bit more overhead - not anything to worry or even think about in most circumstances, but theoretically it might matter in extraordinary circumstances.

我还想提一下,如果您查看 jQuery 源代码(在 jquery-1.7.1.js 中),您会看到.click()(或.keyup()等)函数在内部实际上会调用.on()or .trigger()。显然,这意味着您可以确信它们确实具有相同的结果,但这也意味着使用.click()会产生更多的开销 - 在大多数情况下无需担心甚至考虑,但理论上在特殊情况下可能很重要。

EDIT: Finally, note that .on()allows you to bind several events to the same function in one line, e.g.:

编辑:最后,请注意,.on()允许您在一行中将多个事件绑定到同一个函数,例如:

$("#whatever").on("click keypress focus", function(){});

回答by dana

They appear to be the same... Documentation from the click()function:

它们似乎是相同的...来自click()函数的文档:

This method is a shortcut for .bind('click', handler)

此方法是 .bind('click', handler) 的快捷方式

Documentation from the on()function:

on()函数的文档:

As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers. For help in converting from older jQuery event methods, see .bind(), .delegate(), and .live(). To remove events bound with .on(), see .off().

从 jQuery 1.7 开始, .on() 方法提供了附加事件处理程序所需的所有功能。有关从旧 jQuery 事件方法转换的帮助,请参阅 .bind()、.delegate() 和 .live()。要删除与 .on() 绑定的事件,请参阅 .off()。

回答by SLaks

No, there isn't.
The point of on()is its other overloads, and the ability to handle events that don't have shortcut methods.

不,没有。
重点on()是它的其他重载,以及处理没有快捷方法的事件的能力。

回答by Ramesh kumar

.clickevents only work when element gets rendered and are only attached to elements loaded when the DOM is ready.

.click事件仅在元素被渲染时起作用,并且仅在 DOM 准备就绪时附加到加载的元素上。

.onevents are dynamically attached to DOM elements, which is helpful when you want to attach an event to DOM elements that are rendered on ajax request or something else (after the DOM is ready).

.on事件动态附加到 DOM 元素,当您想将事件附加到在 ajax 请求或其他内容上呈现的 DOM 元素时(在 DOM 准备好之后),这很有用。

回答by Mustkeem K

Here you will get list of diffrent ways of applying the click event. You can select accordingly as suaitable or if your click is not working just try an alternative out of these.

在这里,您将获得应用点击事件的不同方式的列表。您可以相应地选择合适的,或者如果您的点击不起作用,请尝试其中的替代方案。

$('.clickHere').click(function(){ 
     // this is flat click. this event will be attatched 
     //to element if element is available in 
     //dom at the time when JS loaded. 

  // do your stuff
});

$('.clickHere').on('click', function(){ 
    // same as first one

    // do your stuff
})

$(document).on('click', '.clickHere', function(){
          // this is diffrent type 
          //  of click. The click will be registered on document when JS 
          //  loaded and will delegate to the '.clickHere ' element. This is 
          //  called event delegation 
   // do your stuff
});

$('body').on('click', '.clickHere', function(){
   // This is same as 3rd 
   // point. Here we used body instead of document/

   // do your stuff
});

$('.clickHere').off().on('click', function(){ // 
    // deregister event listener if any and register the event again. This 
    // prevents the duplicate event resistration on same element. 
    // do your stuff
})

回答by tw0shoes

They've now deprecated click(), so best to go with on('click')

他们现在已经弃用了 click(),所以最好使用 on('click')

回答by Alper Bilgil

As far as ilearned from internet and some friends .on() is used when you dynamically add elements. But when i used it in a simple login page where click event should send AJAX to node.js and at return append new elements it started to call multi-AJAX calls. When i changed it to click() everything went right. Actually i did not faced with this problem before.

据我从网上和一些朋友了解到,动态添加元素时使用 .on() 。但是当我在一个简单的登录页面中使用它时,点击事件应该将 AJAX 发送到 node.js 并在返回时附加新元素,它开始调用多 AJAX 调用。当我将其更改为 click() 时,一切正常。其实我以前没有遇到过这个问题。