.on('click') 与 .click() 之间的区别 [英] Difference between .on('click') vs .click()

查看:36
本文介绍了.on('click') 与 .click() 之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there any difference between the following code?

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

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

推荐答案

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

I think, the difference is in usage patterns.

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

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

考虑以下 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);
});

并且想要警报!"显示警报.我们可以使用点击"或打开".

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

$("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. 许多匹配的元素会创建许多相同的处理程序,从而增加内存占用
  2. 动态添加的项目不会有处理程序 - 即,在上面的 html 中新添加的警报!"除非您重新绑定处理程序,否则按钮将不起作用.

当我们使用.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.

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

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

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

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!"); });

通过解除绑定

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

这篇关于.on('click') 与 .click() 之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆