`
vateran
  • 浏览: 23642 次
  • 性别: Icon_minigender_1
  • 来自: 大连
社区版块
存档分类
最新评论

bind的问题

阅读更多

想在for循环中动态创建div,然后给每个div bind click事件,需要在监听方法中获取循环的索引。最初的例子如下:

 

<head>
	<script type="text/javascript">
	$(document).ready(function(){
		for(var i = 0; i < 4; i++) {
			$('#id_' + i).bind("click", function() {
				alert($(this).text() + ", i = " + i);
			});
		}
	});
	</script>
	<style>
	<!--
		.page {
			width: 200px;
			height: 50px;
			border: 1px solid blue;
			margin-bottom: 10px;
		}
	-->
	</style>
</head>
<body>
	<div class="page" id="id_0">a</div>
	<div class="page" id="id_1">b</div>
	<div class="page" id="id_2">c</div>
	<div class="page" id="id_3">d</div>
</body>

 

可是运行的结果令我很差异。后来改为使用$('.page').each(function(i){}调用循环得到了预定的结果。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics