softwarefang

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 });

 

 


分类:

技术点:

相关文章:

  • 2022-12-23
  • 2021-12-06
  • 2022-12-23
  • 2021-09-12
  • 2021-05-30
  • 2022-02-16
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-02-15
  • 2022-12-23
  • 2021-12-08
  • 2022-12-23
相关资源
相似解决方案