jquery中綁定事件一般使用bind,或者click,但是這只能是對已經加載好的元素定義事件,那些后來添加插入的元素則需要另行綁定。在1.7版本以前使用live。但是在1.8版本以后推薦使用on。這里介紹jQuery中如何給動態添加的元素綁定事件
在實際開發中會遇到要給動態生成的html元素綁定觸發事件的情況
例如
1 <div id="testdiv"> 2 <ul></ul> 3 </div>
需要給<ul>里面動態添加的<li>標簽添加click事件
jquery 1.7版以前使用live動態綁定事件
$("#testdiv ul li").live("click",function(){
//do something here
});
jquery 1.7版以后使用on動態綁定事件
1 $("#testdiv ul").on("click","li", function() { 2 //do something here 3 });
