为动态生成的元素添加对应的事件,希望分别警告出来的是0-9,可实际警告出来的一直为10,如何解决呢?<div id="test"></div>
<script>
for (var i = 0; i < 10; i++) {
$("#test").append("<span id='div_" + i + "' style='display:inline-block;background:#ccc;margin:5px;width:50px;height:50px;'>" + i + "</span>");
$("#div_" + i).click(function () {
alert(i); //不能为每一个生成的元素指定事件,alert出来的i永远为10
});
}
</script>
<script>
for (var i = 0; i < 10; i++) {
$("#test").append("<span id='div_" + i + "' style='display:inline-block;background:#ccc;margin:5px;width:50px;height:50px;'>" + i + "</span>");
$("#div_" + i).click(function () {
alert(i); //不能为每一个生成的元素指定事件,alert出来的i永远为10
});
}
</script>
<script>
for (var i = 0; i < 10; i++) {(function(i){
$("#test").append("<span id='div_" + i + "' style='display:inline-block;background:#ccc;margin:5px;width:50px;height:50px;'>" + i + "</span>");
$("#div_" + i).click(function () {
alert(i); //不能为每一个生成的元素指定事件,alert出来的i永远为10
});
})(i)}
</script>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.min.js"></script>
<script>
for (var i = 0; i < 10; i++) {
$("#test").append("<span id='div_" + i + "' style='display:inline-block;background:#ccc;margin:5px;width:50px;height:50px;'>" + i + "</span>");
$("#div_" + i).click(function () {
alert(this.id); //不能为每一个生成的元素指定事件,alert出来的i永远为10
});
}
</script>
for (var i = 0; i < 10; i++) {
$("#test").append("<span id='div_" + i + "' style='display:inline-block;background:#ccc;margin:5px;width:50px;height:50px;'>" + i + "</span>");}
for (var i = 0; i < 10; i++) {
$("#div_" + i).click(function () {
alert(this.id); //不能为每一个生成的元素指定事件,alert出来的i永远为10
});
}