在工作当中,有这样的场景,对于一个按钮,在某些条件下,属于可点击状态,在另一些条件下,属于不可点击状态,可能我们就会通过jQuery动态的绑定事件,解绑事件,但此时,就要小心了,防止自己掉进重复绑定事件的问题上。
1、问题
在jQuery中,对于一个元素标签,是可以进行重复绑定事件的,比如下面的代码,button按钮就绑定了两次click事件,每次点击,触发了两次代码的执行。
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>bind多次绑定问题</title>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function register_click(){
$('#button').click(function(){
alert('button click');
});
}
$(function(){
//重复注册
register_click();
register_click();
//模拟点击,会出现两次alert
$('#button').click();
});
</script>
</head>
<body>
<button id="button">按钮</button>
</body>
</html>
2、解决方法
对于需要重复绑定事件的场景,在注册事件的时候首先unbind后bind,或者先off后on,代码如下:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>bind多次绑定问题</title>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
/*function register_click(){
$('#button').unbind('click').bind('click',function(){
alert('button click');
});
}*/
function register_click(){
$('#button').off('click').on('click',function(){
alert('button click');
});
}
$(function(){
//重复注册
register_click();
register_click();
//模拟点击
$('#button').click();
});
</script>
</head>
<body>
<button id="button">按钮</button>
</body>
</html>