jquery动态绑定事件处理一些由于html代码是动态生成,导致普通的$('selector') 绑定事件失败问题
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>测试</title>
</head>
<body>
<div id="test_div"></div>
<!-- 引入jquery,这里需要改成你们自己的路径 -->
<script type="text/ecmascript" src="resources/common/js/include.js"></script>
<script type="text/javascript">
$(function(){
var html='<button class="test_btn">动态生成按钮</button>';
//动态代码添加到div中
$('#test_div').append(html);
//普通绑定事件方式绑定刚添加的代码中的button点击事件
$('.test_btn').click(function(){
alert("按钮被点击到了");
});
})
</script>
</body>
</html>
解决办法:
使用document
代理绑定事件,参考下面代码
//动态绑定,其实就是将绑定事件交给document托管;格式 $(document).on('事件名','jquery选择器',function(){});
$(document).on('click','.test_btn',function(){
alert('动态绑定生效了');
})
http://blog.xqlee.com/article/3.html