.on('click') 与 .click() 之间的区别

发布于 2025-01-02 04:29:57 字数 215 浏览 2 评论 0原文

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

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

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

Is there any difference between the following code?

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

and

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

や三分注定 2025-01-09 04:29:57

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

我更喜欢 .on 而不是 .click,因为前者可以使用更少的内存并可用于动态添加的元素。

考虑以下 html:

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

我们通过其中添加新按钮

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

并希望“警报!”显示警报。我们可以使用“click”或“on”来实现。


当我们

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

在上面使用 click 时,将为与选择器匹配的每个元素创建一个单独的处理程序。这意味着

  1. 许多匹配元素将创建许多相同的处理程序,从而增加内存占用,
  2. 动态添加的项目将没有处理程序 - 即,在上面的 html 中新添加的“Alert!”除非您重新绑定处理程序,否则按钮将不起作用。

当我们将 .on

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

与上面的内容一起使用时,单个处理程序将处理与您的选择器匹配的所有元素,包括动态创建的元素。


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

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

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

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

通过解除绑定

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

I think, the difference is in usage patterns.

I would prefer .on over .click because the former can use less memory and work for dynamically added elements.

Consider the following 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.


When we use click

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

with the above, a separate handler gets created for every single element that 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.

When we use .on

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

with the above, a single handler for all elements that match your selector, including the ones created dynamically.


...another reason to use .on

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

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:

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

with unbinding via

$("#element").off("click.someNamespace");
拔了角的鹿 2025-01-09 04:29:57

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

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

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

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

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():

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.

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

谜泪 2025-01-09 04:29:57

自 jQuery 1.7 起,推荐使用 .on() 进行所有事件绑定。它将 .bind().live() 的所有功能整合到一个函数中,当您向其传递不同的参数时,该函数会改变行为。

正如您所写的示例一样,两者之间没有区别。两者都将处理程序绑定到 #whateverclick 事件。 on() 提供了额外的灵活性,允许您将 #whatever 的子级触发的事件委托给单个处理函数(如果您选择)。

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

.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.

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

// Bind to all links inside #whatever, even new ones created later.
$('#whatever').on('click', 'a', function() { ... });
信愁 2025-01-09 04:29:57

正如其他答案所提到的:

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

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

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

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

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

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

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

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

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

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()).

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

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

$("#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().

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.

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

$("#whatever").on("click keypress focus", function(){});
哭了丶谁疼 2025-01-09 04:29:57

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

.on 事件动态附加到 DOM 元素,当您想要将事件附加到通过 ajax 请求或其他方式呈现的 DOM 元素(在 DOM 准备好之后)时,这非常有用。

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

.on events 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).

飘逸的'云 2025-01-09 04:29:57

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

$('.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
})

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
})
青春如此纠结 2025-01-09 04:29:57

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

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

寻梦旅人 2025-01-09 04:29:57

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

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

此方法是on() 函数中的

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

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

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

Documentation from the on() function:

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().

诗酒趁年少 2025-01-09 04:29:57

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

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

橘虞初梦 2025-01-09 04:29:57

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

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.

弥枳 2025-01-09 04:29:57
$('.UPDATE').click(function(){ }); **V/S**    
$(document).on('click','.UPDATE',function(){ });

$(document).on('click','.UPDATE',function(){ });
  1. 它比 $('.UPDATE').click(function(){ }); 更有效
  2. 它可以使用更少的内存并适用于动态添加的元素。
  3. 有时,使用编辑和删除按钮动态获取的数据在编辑或删除表单中的行数据数据时不会生成 JQuery 事件,此时 $(document).on('click','.UPDATE',function( ){ }); 与使用 jquery 获取的数据一样有效。更新或删除时按钮不起作用:

在此处输入图像描述

$('.UPDATE').click(function(){ }); **V/S**    
$(document).on('click','.UPDATE',function(){ });

$(document).on('click','.UPDATE',function(){ });
  1. it is more effective then $('.UPDATE').click(function(){ });
  2. it can use less memory and work for dynamically added elements.
  3. some time dynamic fetched data with edit and delete button not generate JQuery event at time of EDIT OR DELETE DATA of row data in form, that time $(document).on('click','.UPDATE',function(){ }); is effectively work like same fetched data by using jquery. button not working at time of update or delete:

enter image description here

红颜悴 2025-01-09 04:29:57

新元素

作为上述综合答案的附录,如果您希望单击附加到新元素,请突出显示关键点:

  1. 第一个选择器选择的元素,例如 $("body") 必须在声明时存在,否则会出现没有什么可以附加的。
  2. 您必须使用 .on() 函数中的三个参数,包括目标元素的有效选择器作为第二个参数。

NEW ELEMENTS

As an addendum to the comprehensive answers above to highlight critical points if you want the click to attach to new elements:

  1. elements selected by the first selector eg $("body") must exist at the time the declaration is made otherwise there is nothing to attach to.
  2. you must use the three arguments in the .on() function including the valid selector for your target elements as the second argument.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文