jQuery中delegate与on的用法与区别

Posted skiwnchqhh

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了jQuery中delegate与on的用法与区别相关的知识,希望对你有一定的参考价值。

在jQuery1.7中 .delegate()已被.on()取代。对于早期版本,它仍然使用事件委托的最有效手段。
在事件绑定和委派,delegate()和on在一般情况下,这两种方法是等效的。

.delegate() 指定的元素(属于被选元素的子元素)添加一个或多个事件处理程序,并规定当这些事件发生时运行的函数。

 

// jQuery 1.4.3+
$( elements ).delegate( selector, events, data, handler );
// jQuery 1.7+
$( elements ).on( events, [selector], data, handler );

例如:.delegate()  code:

 

 

$("table").delegate("td","click",function(){
	alert("hello");
});

.on()  code:
$("table").on("click", "td", function() {
        alert("hi");
});

PS: 两者区别是seleter和events顺序不同
delegate和on方法被选元素的子元素必须是"合法的"子元素。比如

 

 

$("table").delegate("button","click",function(){...});
$("table").on("click", "p", function(){...});
就不起作用,因为正常情况下,table子元素应为tr,td...

 

on(events,[selector],[data],fn),参数[selector]是可选,
一个选择器字符串用于过滤器的触发事件的选择器元素的后代。
例如:

$("table").on("click", ".td1", function() {
       alert("hi");
});
过滤class为td1的table子元素

而delegate的selector是必需的。

 

 




再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow


















以上是关于jQuery中delegate与on的用法与区别的主要内容,如果未能解决你的问题,请参考以下文章

jQuery中 .bind() .live(). delegate() . on() 的区别

jquery中bind,live,delegate,on的区别

jquery中bind,live,delegate,on的区别

jQuery事件绑定on()bind()live()与delegate() 方法详解

jQuery中.bind() .live() .delegate() .on()区别

jQuery绑定事物处理器