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();
    });
    

      

      

  • 相关阅读:
    生产环境Redis中的热点key如何发现并优化?
    一条update SQL在MySQL中结束生命历程
    主从测试过程中,如何模拟网络抖动?
    RDS-MySQL物理备份文件恢复到自建数据库
    Python从数据库中读取数据,并打印表格展示数据。
    Python简单巡检MySQL
    RDS-MySQL备份文件恢复到自建数据库
    使用Python读取Excel表格
    设计模式六大原则:迪米特法则
    设计模式六大原则:开闭原则
  • 原文地址:https://www.cnblogs.com/cyj7/p/5110621.html
Copyright © 2011-2022 走看看