JQuery在循环中绑定事件

有个页面上需要N个DOM,每个DOM里面的元素ID都要以数字结尾,比如说

1
2
3
4
5
<input type="text" name="username" id="username_1" value="" />

<input type="text" name="username" id="username_2" value="" />

<input type="text" name="username" id="username_3" value="" />

现在有个循环,在页面载入的时候需要给这每个元素增加一个onclick事件,很容易想到的写法就是

1
2
3
4
5
6
7
$(function(){  
for(var i=1; i<=3; i++){
$('#username_'+i).onclick(function(){
alert(i);
});
}
});

这么写是错误的。。。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<html>

<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function () {
var array = [0, 1, 2, 3];

// 1.
/*
for(var index in array) {
$("#btn" + index).click(function() {
var item = array[index];
alert(item);
});
}*/
// 始终弹出3, 因为function() {} 并没有被立即解析,直到调用的时候才被解析,这时index已经是3了。


// 2.
/*
for(var index in array) {
$("#btn" + index).click(function(i) {
var item = array[i];
alert(item);
}(index));
}*/
// 立即弹出0, 1, 2, 3,因为使用了function() {}(index)立即被解析,遇到alert,就立即弹出来了。


// 3.
/*for (var index in array) {
$("#btn" + index).click(function (i) {
return function () {
var item = array[i];
alert(item);
};
} (index));
}*/
// 正确执行,点击btn0,弹出0,点击btn1,弹出1...
// 1.因为function(i) {}(index)是被立即解析的,所以i依次送入的是0, 1, 2, 3
// 2.内部没有直接alert,是因为不想立即执行,想点击时再执行,所以返回了一个函数出去。


// 4.
for (var index in array) {
$("#btn" + index).bind("click", {index: index}, clickHandler);
}

function clickHandler(event) {
var index = event.data.index;
var item = array[index];
alert(item);
}
// 正确执行,点击btn0,弹出0,点击btn1,弹出1...
// 利用了event.data,因为index在绑定的时候已经被持久化到event.data中了,所以响应的时候我们可以取到。
});

</script>

<input type="button" id="btn0" value="btn0" />
<input type="button" id="btn1" value="btn1" />
<input type="button" id="btn2" value="btn2" />
<input type="button" id="btn3" value="btn3" />
</body>
</html>

扩展阅读:jQuery如何给动态生成的元素绑定事件live/on