日期:2014-05-16  浏览次数:20419 次

jquery添加的新节点触发无效?
<!DOCTYPE html>

<meta charset=utf-8>

<html>

<head>

<style type="text/css">

.main{border:1px solid red;min-height:100px;width:500px;}

.main .app{cursor:pointer;}

</style>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

</head>

<body>

<div class="main">

<div class="app">Good_Old</div>

</div>

<input type="button" value="TEST">

<script>

$(document).ready(function(){

$(".app").click(function(){

  alert(123);

})

$("input[type=button]").click(function(){

$(".main").append('<div class="app">Good_New</div>');

})

})

</script>

</body>

</html>

测试发现Old正常,新添的New节点不会弹出123

高手指点



------解决方案--------------------
jquery 绑定事件的时候是用 live方法 $(".app").live('click',function(){})
------解决方案--------------------
$(".app").live('click', function(){

alert(123);

})


------解决方案--------------------
我这样理解
文档准备好进行事件绑定的时候,新节点并不存在。
所以即使你 通过 按钮 添加了N个新节点,事件绑定早已经完成。所以新节点就无效果了
------解决方案--------------------
1.7+版本应该使用on()方法来绑定:
JScript code
$(document).on('click', '.app', function() { alert('123'); });