jQuery无法绑定新增元素click事件的解决方案

来源:互联网 发布:php 文件上传插件 编辑:程序博客网 时间:2024/05/17 02:57
$(".document_arrow_down").click(function(){alert("document_arrow_down click");resetDocumentBtn()$(this).hide();$(this).siblings(".document_arrow_up").show();$(this).parent().siblings(".document_btn_box").show();});


上面的代码可以绑定原页面已有的元素,但对于新添加的元素却绑定失败,查看chrome的event listeners,看不到这个事件,下图是静态元素的结果


下图是动态元素的结果


原因是“绑定”这一事件发生在生成元素之前,新生成的元素没有触发。改法是用on方法,前面绑定一个静态元素,后面选择要绑定的静态元素

$("#document_box").on("click", "li .document_info .document_arrow_down",function(){resetDocumentBtn()$(this).hide();$(this).siblings(".document_arrow_up").show();$(this).parent().siblings(".document_btn_box").show();});
这样在chrome的event listeners里依然看不到,但可以生效。猜想event listeners只有静态的绑定事件。



0 0
原创粉丝点击