当前位置: 代码迷 >> Web前端 >> bind的有关问题
  详细解决方案

bind的有关问题

热度:283   发布时间:2012-10-19 16:53:35.0
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){}调用循环得到了预定的结果。

  相关解决方案