jquery 事件绑定on bind delegate区别

W3C事件模型中的事件,首先进入捕获阶段由外向内直达目标元素,再进入冒泡阶段。支持W3C模型的浏览器传统的事件绑定属于冒泡。javascript

jquery事件绑定中on bind delegate区别联系

bind和delegate都是由on实现的,jquery文档也推荐使用onjava

bind: function( types, data, fn ) {
     return this.on( types, null, data, fn );
    },
    unbind: function( types, fn ) {
     return this.off( types, null, fn );
    },
    delegate: function( selector, types, data, fn ) {
     return this.on( types, selector, data, fn );
    }
    undelegate: function( selector, types, fn ) {
 // ( namespace ) or ( selector, types [, fn] )
     return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
    }

那么如今就bind和delegate区别jquery

bind方法使用浏览器

$("div p").bind("click", function () {
    alert($(this).text());
})

性能

$("div p").click(function () {
    alert($(this).text());
})

此方法只能为已存在元素绑定事件,在动态添加节点出现事件失效(需为新元素从新绑定事件,而且已有事件最好手动移除,否则会堆积占内存)。this

delegate方法使用spa

$("div").delegate("p", "click", function () {
    alert($(this).text());
});

此方法使用事件委托方式将事件委托给上层节点处理,很好的避免了动态添加节点重复绑定解绑,但须要注意节点绑定委托不要太深否则影响性能。code

相关文章
相关标签/搜索