如何为动态刷新出来的元素绑定JQuery事件?

已邀请:

zkbhj - 凯冰科技站长

赞同来自:

常规的事件绑定方式为:jQuery on()方法是官方推荐的绑定事件的一个方法。
$(selector).on(event,childSelector,data,function,map)
由此扩展开来的几个以前常见的方法有:
bind() 
$("p").bind("click",function(){ alert("The paragraph was clicked."); });
$("p").on("click",function(){ alert("The paragraph was clicked."); });

delegate()
$(document).ready(function(){ $("#div1").on("click","p",function(){ $(this).css("background-color","pink"); });
$("#div2").delegate("p","click",function(){ $(this).css("background-color","pink"); }); });

live()
$(document).ready(function(){ $("#div1").on("click",function(){ $(this).css("background-color","pink"); });
$("#div2").live("click",function(){ $(this).css("background-color","pink"); }); });
以上三种方法在jQuery1.8之后都不推荐使用,官方在1.9时已经取消使用live()方法了,所以建议都使用on()方法。 
如果要给动态生成的元素绑定事件,可以使用:$(document).on()。
 
//喜欢歌曲
$(document).on('click', '.song-like', function(){
alert('like song!');
});


$(document).on是把事件委托到document上,$('className').on是把事件绑定到.className元素上。
效率方面,直接绑定在元素上会更为高效,绑定在document上,每次document有点击动作,浏览器都会判断当前点击的对象,如果匹配,再决定要不要执行,多了一个判断的环节。
但在目前开发中,JS渲染效率很高,所以此异同基本可以忽略不计。
此外,针对$(document).on的触发特点,延伸一下,$("className").on为onclick绑定,只有在页面onload的时候执行一次,当页面刷新后,新加载的具有className的元素便没有事件绑定到上面了,相反$(document).on这种方法会刷新和重新赋予绑定操作,所以一定程度上更为全面。

要回复问题请先登录注册