jQuery中防止重复绑定事件的问题

在工作当中,有这样的场景,对于一个按钮,在某些条件下,属于可点击状态,在另一些条件下,属于不可点击状态,可能我们就会通过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>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值