`on`和`live`或`bind`有什么区别? [英] What's the difference between `on` and `live` or `bind`?

查看:117
本文介绍了`on`和`live`或`bind`有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在jQuery v1.7 中,一种新方法, on 被添加。从文档中:


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


的区别 bind

解决方案

on()是将大部分jQuery的事件绑定函数合并成一个。这个额外的好处是可以使用 live vs delegate 来整理效率低下。在将来的jQuery版本中,这些方法将被删除,只有和一个之间的将保留。



示例:

  //使用live()
$( .mySelector)。live(click,fn);

//等效的`on`(没有完全相同但有很好的理由)
$(document).on(click,.mySelector,fn) ;





  //使用绑定()
$(。mySelector)。bind(click,fn);

//等效`on`
$(。mySelector)。on(click,fn);





  //使用代理()
$(document.body).delegate(。mySelector,click,fn);

//等效`on`
$(document.body).on(click,.mySelector,fn);

在内部,jQuery映射所有这些方法 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);
返回这个;
},
委托:function(selector,types,data,fn){
return this.on(types,selector,data,fn);
},

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


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

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

What's the difference with live and bind?

解决方案

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 live vs delegate. In future versions of jQuery, these methods will be removed and only on and one will be left.

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 all these methods and shorthand event handler setters to the on() method, further indicating that you should ignore these methods from now on and just use 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.

这篇关于`on`和`live`或`bind`有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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