jQuery 1.10之前的版本有一个.live()方法,这个方法和bind的重要区别就是.live()方法可以对以后再添加进来的有效
例如如下的HTML:
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
</title>
<script src="jquery-1.8.0.js" type="text/javascript"></script>
<body>
<span>Hello</span><br/>
<input type="button" id="btnCancel" class="button" value="测试" οnclick="javascript:test()" />
<div id="testdiv"></div>
</body>
</html>
使用bind方法:
$(document).ready(function () {
$('span').bind('click',function() {
alert( "333" );
})
});
function test(){
$("#testdiv").append("<span>Hello</span><br/>");
}
则只有已经存在的那一个span能绑定上 click事件,对于通过test()后添加的span是没有绑定click事件的,如果还需要给后来添加的span绑定则必须重新绑定一次
例如:
$(document).ready(function () {
$('span').bind('click',function() {
alert( "333" );
})
});
function test(){
$("#testdiv").append("<span>Hello</span><br/>");
$("span").unbind( "click" )// 去掉原来的绑定
$('span').bind('click',function() {//重新绑定
alert( "333" );
})
这样以后 通过 test() 后添加的 span也就绑定了事件。
其实还有更简单的方法,就是使用live,例如:
$(document).ready(function () {
$('span').live('click',function() {
alert( "333" );
})
});
function test(){
$("#testdiv").append("<span>Hello</span><br/>");
}
但在 jQuery 1.10之后,没有了live方法,变成了on方法,如何使用呢?
$(document).ready(function () {
$('span').on('click',function() {
alert( "333" );
})
});
function test(){
$("#testdiv").append("<span>Hello</span><br/>");
}
测试发现,还是只对存在的span绑定的方法,通过 test() 后添加的 span是没有绑定 click事件的,那对于使用live方法绑定的如何替换呢?
其实可以这样写:
$(document).ready(function () {
$(document).on('click', 'span', function() {
alert( "333" );
})
});
function test(){
$("#testdiv").append("<span>Hello</span><br/>");
}
当然也可以这样写:
$(document).ready(function () {
$("body").on('click', 'span', function() {
alert( "333" );
})
});
function test(){
$("#testdiv").append("<span>Hello</span><br/>");
}
本质其实是绑定在了父元素(body)上,再根据父元素找满足条件的子元素(span),这样性能就会有所提升,所以替换live方法,就需要使用on在父元素的绑定,而不是简单的把字符live替换为on