码迷,mamicode.com
首页 > Web开发 > 详细

js 代码位置不同,导致随着点击函数执行次数累加

时间:2016-01-07 18:09:04      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:

每个人书写代码的习惯都不同吃,思想也都不一样,但在工作中为了减少工作量与时间,难免遇到要用别人写的代码。这次在使用同事的代码中,偶然发现的问题,因为js不好,所以一眼也没发现问题所在,查了查网上才知道这是由于重复绑定导致的。如下所示:

function showAlt(){
	if($("div.alert").length > 0){
		$("div.alert").show();
	}else{
		var html = ‘<div class="alert" style="border:1px solid #ccc; padding:20px;">hello world!</div>‘;
		$("body").append(html);
	}
	$(".alert").on("click",function(){
		console.log("alert1");
		$(this).hide();
	});
}
$("#login").click(function(){
	showAlt();
});

那么,每次点击无论div.alert是否存在、是否绑定过函数,都会再次绑定函数,这就导致了函数多次绑定与多次执行,解决办法如下:

方法1. 在首次加载该标签时绑定即可,如果页面已存在节点说明其已经绑定过,无需再绑定,这样就避免了函数的多次绑定与执行。

function showAlt(){
	if($("div.alert").length > 0){
		$("div.alert").show();
	}else{
		var html = ‘<div class="alert" style="border:1px solid #ccc; padding:20px;">hello world!</div>‘;
		$("body").append(html);
		$(".alert").on("click",function(){
			console.log("alert1");
			$(this).hide();
		});
	}
}

方法2. 每次绑定前先解绑,这里用到了unbind()

function showAlt(){
	if($("div.alert").length > 0){
		$("div.alert").show();
	}else{
		var html = ‘<div class="alert" style="border:1px solid #ccc; padding:20px;">hello world!</div>‘;
		$("body").append(html);
	}
	$(".alert").unbind("click").on("click",function(){
		console.log("alert1");
		$(this).hide();
	});
}

如果用的是方法live(貌似jq1.8版本后就取消了这个函数了)绑定的函数,那就需要die()了

方法3. 使用事件委托为标签绑定函数,事件委托的方法有on()、delegate(),这里就不过多介绍了

function showAlt(){
	if($("div.alert").length > 0){
		$("div.alert").show();
	}else{
		var html = ‘<div class="alert" style="border:1px solid #ccc; padding:20px;">hello world!</div>‘;
		$("body").append(html);
	}
}
$("body").on("click",".alert",function(){
	console.log("alert1");
	$(this).hide();
});

  

 

  

 

js 代码位置不同,导致随着点击函数执行次数累加

标签:

原文地址:http://www.cnblogs.com/cyj7/p/5110621.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!