安蝶

前端学习ing

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

每个人书写代码的习惯都不同吃,思想也都不一样,但在工作中为了减少工作量与时间,难免遇到要用别人写的代码。这次在使用同事的代码中,偶然发现的问题,因为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();
});

  

 

  

 

posted on 2016-01-07 17:29  安蝶  阅读(459)  评论(0编辑  收藏  举报