jQuery “on”和“live”或“bind”有什么区别?

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

What's the difference between `on` and `live` or `bind`?

jquery

提问by Diego

In jQuery v1.7a new method, onwas added. From the documentation:

在 jQuery v1.7on中添加了一个新方法。从文档:

‘The .on() method attaches event handlers to the currently selected set of elements in the jQuery object. As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers.'

'.on() 方法将事件处理程序附加到 jQuery 对象中当前选定的一组元素。从 jQuery 1.7 开始,.on() 方法提供了附加事件处理程序所需的所有功能。

What's the difference with liveand bind?

什么是与差异livebind

回答by Andy E

on()is an attempt to merge most of jQuery's event binding functions into one. This has the added bonus of tidying up the inefficiencies with livevs delegate. In future versions of jQuery, these methods will be removed and only onand onewill be left.

on()试图将 jQuery 的大部分事件绑定功能合并为一个。这有一个额外的好处,就是用livevs来整理效率低下的地方delegate。在 jQuery 的未来版本中,这些方法将被删除,on并且one只会被保留。

Examples:

例子:

// Using live()
$(".mySelector").live("click", fn);

// Equivalent `on` (there isn't an exact equivalent, but with good reason)
$(document).on("click", ".mySelector", fn);
// Using bind()
$(".mySelector").bind("click", fn);

// Equivalent `on`
$(".mySelector").on("click", fn);
// Using delegate()
$(document.body).delegate(".mySelector", "click", fn);

// Equivalent `on`
$(document.body).on("click", ".mySelector", fn);

Internally, jQuery maps allthese methods andshorthand event handler setters to the on()method, further indicating that you should ignore these methods from now on and just use on:

在内部,jQuery 将所有这些方法速记事件处理程序设置器映射到该on()方法,进一步表明您应该从现在开始忽略这些方法并只使用on

bind: function( types, data, fn ) {
    return this.on( types, null, data, fn );
},
live: function( types, data, fn ) {
    jQuery( this.context ).on( types, this.selector, data, fn );
    return this;
},
delegate: function( selector, types, data, fn ) {
    return this.on( types, selector, data, fn );
},

See https://github.com/jquery/jquery/blob/1.7/src/event.js#L965.

请参阅https://github.com/jquery/jquery/blob/1.7/src/event.js#L965

回答by roselan

onis in nature very close to delegate. So why not use delegate? It's because ondoesn't come alone. there's off, to unbind event and oneto create an event to be executed one time only. This is a new event's "package".

on本质上是非常接近的delegate。那么为什么不使用委托呢?那是因为on不是一个人来。有off, 取消绑定事件并one创建仅执行一次的事件。这是一个新事件的“包”。

The main problem of liveis that it attaches to "window", forcing a click event (or other event) on an element deep inside the page structure (the dom), to "bubble up" to the top of the page to find an event handler willing to deal with it. At each level, all event handlers have to be checked, this can add up fast, if you do deep imbrication (<body><div><div><div><div><table><table><tbody><tr><td><div><div><div><ul><li><button> etc etc etc...)

的主要问题live是它附加到“窗口”,强制页面结构(dom)深处的元素上的点击事件(或其他事件)“冒泡”到页面顶部以查找事件处理者愿意处理它。在每个级别,都必须检查所有事件处理程序,如果您进行深度覆盖,这可以快速加起来 ( <body><div><div><div><div><table><table><tbody><tr><td><div><div><div><ul><li><button> etc etc etc...)

So, bind, like click, like other shortcut event binders attach directly to the event target. If you have a table of, let's say, 1000 lines and 100 columns, and each of the 100'000 cells includes a checkbox which click you want to handle. Attaching 100'000 event handlers will take a lotof time on page load. Creating a single event at the table level, and using event delegation is several orders of magnitude more efficient. The event target will be retrieved at event execution time. "this" will be the table, but "event.target" will be your usual "this" in a clickfunction. Now the nice thing with onis that "this" will always be the event target, and not the container it is attached to.

所以,bindclick,像其他快捷事件绑定器一样直接附加到事件目标。如果您有一个表格,比方说,1000 行和 100 列,并且 100'000 个单元格中的每一个都包含一个复选框,您可以单击该复选框来处理。附加 100'000 个事件处理程序将在页面加载上花费大量时间。在表级别创建单个事件,并使用事件委托效率高几个数量级。将在事件执行时检索事件目标。" this" 将是表,但 " event.target" 将是您thisclick函数中常用的 " " 。现在的好处on是“ this”将始终是事件目标,而不是它附加到的容器。

回答by Esailija

with .onmethod it is possible to do .live, .delegate, and .bindwith the same function but with .live()only .live()is possible ( delegating events to document ).

with.on方法可以做.live, .delegate, 和.bind使用相同的功能,但 with .live()only.live()是可能的(将事件委托给文档)。

jQuery("#example").bind( "click", fn )= jQuery( "#example").on( "click", fn );

jQuery("#example").bind( "click", fn )= jQuery( "#example").on( "click", fn );

jQuery("#example").delegate( ".examples", "click", fn )= jQuery( "#example" ).on( "click", ".examples", fn )

jQuery("#example").delegate( ".examples", "click", fn )= jQuery( "#example" ).on( "click", ".examples", fn )

jQuery("#example").live( fn )= jQuery( document ).on( "click", "#example", fn )

jQuery("#example").live( fn )= jQuery( document ).on( "click", "#example", fn )

I can confirm this directly from jQuery source:

我可以直接从 jQuery 源代码中确认这一点:

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

live: function( types, data, fn ) {
    jQuery( this.context ).on( types, this.selector, data, fn );
    return this;
},

delegate: function( selector, types, data, fn ) {
    return this.on( types, selector, data, fn );
},

jQuery( this.context )? this.context=== documentin most cases

jQuery(this.context)?this.context===document在大多数情况下

回答by T.J. Crowder

(My opening sentence made more sense before you changed the question. Originally you'd said "What's the difference with live?")

(在你改变问题之前,我的开场白更有意义。最初你说“和 有什么区别live?”)

onis more like delegatethan it is like live, it's basically a unified form of bindand delegate(in fact, the team said its purpose is "...to unify all the ways of attaching events to a document...").

on更像delegatelive,它基本上是bindand的统一形式delegate(实际上,团队说它的目的是“......统一将事件附加到文档的所有方式......”)。

liveis basically on(or delegate) attached to the document as a whole. It's deprecated as of v1.7in favor of using onor delegate. Going forward, I suspect we'll see code using onsolely, rather than using bindor delegate(or live)...

live基本上on(或delegate)附加到整个文档。从v1.7 开始,它已被弃用,转而使用onor delegate。展望未来,我怀疑我们会看到代码on单独使用,而不是使用bindor delegate(或live)...

So in practice, you can:

所以在实践中,你可以:

  1. Use onlike bind:

    /* Old: */ $(".foo").bind("click", handler);
    /* New: */ $(".foo").on("click", handler);
    
  2. Use onlike delegate(event delegation rooted in a given element):

    /* Old: */ $("#container").delegate(".foo", "click", handler);
    /* New: */ $("#container").on("click", ".foo", handler);
    
  3. Use onlike live(event delegation rooted in the document):

    /* Old: */ $(".foo").live("click", handler);
    /* New: */ $(document).on("click", ".foo", handler);
    
  1. on像这样使用bind

    /* Old: */ $(".foo").bind("click", handler);
    /* New: */ $(".foo").on("click", handler);
    
  2. 使用onlike delegate(基于给定元素的事件委托):

    /* Old: */ $("#container").delegate(".foo", "click", handler);
    /* New: */ $("#container").on("click", ".foo", handler);
    
  3. 使用onlike live(基于文档的事件委托):

    /* Old: */ $(".foo").live("click", handler);
    /* New: */ $(document).on("click", ".foo", handler);
    

回答by doochik

live is the shortcut for .on() now

live 是 .on() 现在的快捷方式

//from source http://code.jquery.com/jquery-1.7.js
live: function( types, data, fn ) {
    jQuery( this.context ).on( types, this.selector, data, fn );
    return this;
}

also this post may be usefull for you http://blog.jquery.com/2011/11/03/jquery-1-7-released/

这篇文章也可能对你有用 http://blog.jquery.com/2011/11/03/jquery-1-7-released/

回答by Dan

There isn't one for the basic use case. These two lines are functionally the same

没有一个用于基本用例。这两行在功能上是一样的

$( '#element' ).bind( 'click', handler );
$( '#element' ).on( 'click', handler );

.on() can also do event delegation, and is preferred.

.on() 也可以做事件委托,是首选。

.bind() is actually just an alias for .on() now. Here's the definition of the bind function in 1.7.1

.bind() 现在实际上只是 .on() 的别名。这里是1.7.1中bind函数的定义

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

The idea for adding .on() was to create a unified event API, rather than having multiple functions for binding event; .on() replaces .bind(), .live() and .delegate().

添加 .on() 的想法是创建一个统一的事件 API,而不是具有多个绑定事件的函数;.on() 替换了 .bind()、.live() 和 .delegate()。

回答by Alexander

Something you should be aware of if you want to get the event handlers associated with the element - pay attention which element the handler was attached to!

如果您想获取与元素关联的事件处理程序,您应该注意的事情 - 注意处理程序附加到哪个元素!

For example, if you use:

例如,如果您使用:

$('.mySelector').bind('click', fn);

you will get the event handlers using:

您将使用以下方法获取事件处理程序:

$('.mySelector').data('events');

But if you use:

但是如果你使用:

$('body').on('click', '.mySelector', fn);

you will get the event handlers using:

您将使用以下方法获取事件处理程序:

$('body').data('events');

(in the last case the relevant event object will have selector=".mySelector")

(在最后一种情况下,相关事件对象将具有选择器 =“.mySelector”)