Javascript jQuery 的 .bind() 与 .on()

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

jQuery’s .bind() vs. .on()

javascriptjqueryjquery-selectors

提问by Samuel

I found two great articles talking about the new function .on(): jquery4u.com, elijahmanor.com.

我发现了两篇关于新功能的很棒的文章.on()jquery4u.comelijahmanor.com

Is there any way where the .bind()still is better to use than .on()?

有什么方法.bind()比使用仍然更好.on()吗?

For example, I have a sample code that look like this:

例如,我有一个如下所示的示例代码:

$("#container").click( function( e ) {} )

You can note that I just have one item retrieved by the selector and in my case, the <div>named #containeralready exists when my page was loaded; not added dynamically. It's important to mention that I use the latest version of jQuery: 1.7.2.

你可以注意到我只有一个被选择器检索到的项目,在我的例子中,当我的页面加载时,<div>named#container已经存在;不是动态添加的。值得一提的是,我使用的是最新版本的 jQuery:1.7.2。

For that sample, should .on()be used instead of .bind()even if I don't use the other features provided by the .on()function?

对于该示例,即使我不使用该函数提供的其他功能,也应该.on()使用它来代替?.bind().on()

回答by Blazemonger

Internally, .bindmaps directly to .onin the current version of jQuery. (The same goes for .live.) So there is a tiny but practically insignificant performance hit if you use .bindinstead.

在内部,.bind直接映射到.on当前版本的 jQuery。(同样适用于.live。)因此,如果您.bind改为使用,则会对性能造成微小但实际上无关紧要的影响。

However, .bindmay be removed from future versions at any time. There is no reason to keep using .bindand every reason to prefer .oninstead.

但是,.bind可以随时从未来版本中删除。没有理由继续使用.bind,也有理由更喜欢.on

回答by jbabey

These snippets all perform exactly the same thing:

这些片段都执行完全相同的事情:

element.on('click', function () { ... });
element.bind('click', function () { ... });
element.click(function () { ... });

However, they are very different from these, which all perform the same thing:

但是,它们与这些非常不同,它们都执行相同的操作:

element.on('click', 'selector', function () { ... });
element.delegate('click', 'selector', function () { ... });
$('selector').live('click', function () { ... });

The second set of event handlers use event delegationand will work for dynamically added elements. Event handlers that use delegation are also much more performant. The first set will not work for dynamically added elements, and are much worse for performance.

第二组事件处理程序使用事件委托并将用于动态添加的元素。使用委托的事件处理程序的性能也更高。第一组不适用于动态添加的元素,而且性能更差。

jQuery's on()function does not introduce any new functionality that did not already exist, it is just an attempt to standardize event handling in jQuery (you no longer have to decide between live, bind, or delegate).

jQuery 的on()函数不会引入任何尚不存在的新功能,它只是尝试标准化 jQuery 中的事件处理(您不再需要在实时、绑定或委托之间做出决定)。

回答by Esailija

The direct methods and .delegateare superior APIs to .onand there is no intention of deprecating them.

直接方法 和.delegate是高级 API,.on并且无意弃用它们。

The direct methods are preferable because your code will be less stringly typed. You will get immediate error when you mistype an event name rather than a silent bug. In my opinion, it's also easier to write and read clickthan on("click"

直接方法更可取,因为您的代码将减少字符串类型。当您错误输入事件名称而不是静默错误时,您将立即收到错误。在我看来,它也更容易读写clickon("click"

The .delegateis superior to .onbecause of the argument's order:

.delegate优于.on由于参数的顺序:

$(elem).delegate( ".selector", {
    click: function() {
    },
    mousemove: function() {
    },
    mouseup: function() {
    },
    mousedown: function() {
    }
});

You know right away it's delegated because, well, it says delegate. You also instantly see the selector.

你马上就知道它是委托的,因为它说的是委托。您还可以立即看到选择器。

With .onit's not immediately clear if it's even delegated and you have to look at the end for the selector:

有了.on它不立即清除,如果它甚至委托,你必须看看到底该选择:

$(elem).on({
    click: function() {
    },
    mousemove: function() {
    },
    mouseup: function() {
    },
    mousedown: function() {
    }
}, "selector" );

Now, the naming of .bindis really terrible and is at face value worse than .on. But .delegatecannot do non-delegated events and there are events that don't have a direct method, so in a rare case like this it could be used but only because you want to make a clean separation between delegated and non-delegated events.

现在,的命名.bind真的很糟糕,从表面上看比.on. 但是.delegate不能执行非委托事件,并且有些事件没有直接方法,因此在这种罕见的情况下可以使用它,但这只是因为您想在委托和非委托事件之间进行明确分离。

回答by andlrc

If you look in the source code for $.fn.bindyou will find that it's just an rewrite function for on:

如果你查看源代码,$.fn.bind你会发现它只是一个重写函数on

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

http://james.padolsey.com/jquery/#v=1.7.2&fn=$.fn.bind

http://james.padolsey.com/jquery/#v=1.7.2&fn=$.fn.bind

回答by Faust

From the jQuery documentation:

来自 jQuery 文档:

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs. For more flexible event binding, see the discussion of event delegation in .on() or .delegate().
从 jQuery 1.7 开始, .on() 方法是将事件处理程序附加到文档的首选方法。对于早期版本, .bind() 方法用于将事件处理程序直接附加到元素。处理程序附加到 jQuery 对象中当前选定的元素,因此这些元素必须在调用 .bind() 时存在。要获得更灵活的事件绑定,请参阅 .on() 或 .delegate() 中事件委托的讨论。

http://api.jquery.com/bind/

http://api.jquery.com/bind/

回答by userG

As of Jquery 3.0 and above .bind has been deprecated and they prefer using .on instead. As @Blazemonger answered earlier that it may be removed and its for sure that it will be removed. For the older versions .bind would also call .on internally and there is no difference between them. Please also see the api for more detail.

从 Jquery 3.0 及更高版本开始,.bind 已被弃用,他们更喜欢使用 .on 代替。正如@Blazemonger 之前回答的那样,它可能会被删除,并且肯定会被删除。对于旧版本 .bind 也会在内部调用 .on 并且它们之间没有区别。另请参阅 api 以获取更多详细信息。

jQuery API documentation for .bind()

.bind() 的 jQuery API 文档