jQuery如何给动态生成的元素绑定事件live/on

jQuery的html()可以给现在元素附加新的元素,innerHTML也可以,那么,如何给这些新生成的元素绑定事件呢?直接在元素还未生成前就绑定肯定是无效的,因为所绑定的元素目前根本不存在。

然而,jQuery为我们提供了一个函数来解决这个问题,它就是.live(),它可以给所有元素绑定事件,不论是已有的,还是将来生成的,比如:

1
2
3
$(‘#div’).live(‘click’,function(){   
//do stuff
});

它还可以同时绑定多个事件:

1
2
3
4
5
6
7
$('.hoverme').live('mouseover mouseout', function(event) {  
if (event.type == 'mouseover') {
// do something on mouseover
} else {
// do something on mouseout
}
});

【实例】

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
<script type="text/javascript" src="http://lib.sinaapp.com/js/jquery/1.7.2/jquery.min.js">  
</script>
<html>
<body>
<input type="button" name="input[]" value="按钮1" />
<input type="button" name="input[]" value="按钮2" />
<input type="button" name="input[]" value="按钮3" />
<a id="add">添加</a>
</body>
</html>
<script type="text/javascript">
$("#add").click(function() {
var inp = $(":input:last").clone();
$(":input:last").after(inp);
})

// 为每一个button绑定onclick事件,alert一下
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
inputs[i].onclick = function() {
alert("我测试一下");
}
}

$(':input').live('click',function() {
alert("我再测");
});
</script>

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
<script type="text/javascript" src="http://lib.sinaapp.com/js/jquery/1.7.2/jquery.min.js">  
</script>
<html>
<body>
<input type="button" name="input[]" value="按钮1" />
<input type="button" name="input[]" value="按钮2" />
<input type="button" name="input[]" value="按钮3" />
<a id="add">添加</a>
</body>
</html>
<script type="text/javascript">
$("#add").click(function() {
var inp = $(":input:last").clone();
inp2 = inp.val("按钮"+($(":input").length+1));
inp3 = inp2.attr("id","a"+($(":input").length+1))
$(":input:last").after(inp3);
})

//为每一个button绑定onclick事件,alert一下
//var inputs = document.getElementsByTagName("input");
//预先加载,inputs.length最大等于3
for (var i = 0; i < 99; i++) {
$("#a"+i).live('click',function(){
alert($(this).val());
})
}

$(':input').live('click',function() {
alert($(this).val());
});
</script>
**注意:**JQuery1.9以后的版本中,live()被[on()](http://www.w3cschool.cc/jquery/event-on.html)代替,使用方法是 `$('body').on('blur', '#editbox', function(){...})`