zoukankan      html  css  js  c++  java
  • js 代码位置不同,导致随着点击函数执行次数累加

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

      

      

  • 相关阅读:
    九度oj 题目1371:最小的K个数
    九度oj 题目1131:合唱队形
    九度oj 题目1450:产生冠军
    九度oj 题目1135:字符串排序
    九度oj 题目1534:数组中第K小的数字
    九度oj 题目1179:阶乘
    九度oj 题目1369:字符串的排列
    九度oj 题目1100:最短路径
    [Luogu] 子串
    [Luogu] 魔法树
  • 原文地址:https://www.cnblogs.com/cyj7/p/5110621.html
Copyright © 2011-2022 走看看