jquery使用绑定vs点击 [英] jquery use of bind vs on click

查看:27
本文介绍了jquery使用绑定vs点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 jquery 中遇到过几种处理点击事件的方法:

I have come across several methods for handling click events in jquery:

绑定:

$('#mydiv').bind('click', function() {
    ...
});

点击:

$('#mydiv').click(function() {
   ...
}

开:

$('mydiv').on('click', function() {
   ...
}

两个问题:

  1. 他们还有其他方法吗?
  2. 我应该使用哪一个,为什么?

更新:

正如大家所建议的那样,我应该更好地阅读文档,并发现我应该使用:

As eveyone has helpfully suggested, I should have read the docs better, and found out that I should use:

on() 或 click(),

on() or click(),

实际上是同一件事.

但是,没有人解释为什么不再推荐使用 bind ?我可能会因为在某处遗漏明显的东西而受到更多的反对,但我在文档中找不到这样做的原因.

However, nobody has explained why bind is no longer recommended ? I'll probably get more downvotes for missing the obvious somewhere, but I can't find a reason for this in the documents.

更新2:

'on' 具有向动态创建的元素添加事件处理程序的有用效果.例如

'on' has the useful effect of being able to add event handlers to dynamically created elements. e.g.

$('body').on('click',".myclass",function() {
    alert("Clicked On MyClass element");
});

此代码向具有myClass"类的元素添加点击处理程序.但是,如果稍后动态添加更多 myClass 元素,它们也会自动获取点击处理程序,而无需显式调用on".据我了解人们所说,这也更有效(见下面的西蒙斯回答).

This code adds a click handler to elements with a class of 'myClass'. However, if more myClass elements are then dynamically added later, they automatically get the click handler as well, without having to explicitly call 'on'. From what I understand people are saying, this is also more efficient (see Simons answer below).

推荐答案

来自bindclick的文档:

绑定:

从 jQuery 1.7 开始,.on() 方法是将事件处理程序附加到文档.

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document.

来源清楚地表明没有理由使用 bind,因为这函数只调用更灵活的 on 函数,甚至没有更短:

The source makes it clear there's no reason to use bind, as this function only calls the more flexible on function without even being shorter :

bind: function( types, data, fn ) {
    return this.on( types, null, data, fn );
},

所以我建议,就像 jQuery 团队一样,忘记旧的 bind 函数,该函数现在已经没用了.它只是为了与旧代码兼容,它仍然存在.

So I'd suggest, just like the jQuery team, to forget the old bind function, which is now useless. It's only for compatibility with older code that it's still here.

点击:

这个方法是.on('click', handler)的快捷方式

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

这个快捷方式当然不如 on 函数强大和灵活,并且不允许委派,但它可以让您编写更短,并且可以说,在应用时更易读的代码.在这一点上意见分歧:一些开发人员认为应该避免它,因为它只是一个捷径,而且还有一个事实是你需要在使用委托时立即将其替换为 on,所以为什么不直接用on更一致?

This shortcut is of course less powerful and flexible than the on function and doesn't allow delegation but it lets you write a shorter and, arguably, slightly more readable, code when it applies. Opinions diverge on that point : some developers argue that it should be avoided as it is just a shortcut, and there's also the fact that you need to replace it with on as soon as you use delegation, so why not directly use on to be more consistent ?

这篇关于jquery使用绑定vs点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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