JS: javascript 点击事件执行两次js问题 ,解决jquery绑定click事件出现点击一次执行两次问题

javascript 点击事件执行两次js问题

在JQuery中存在unbind()方法先解绑再添加点击事件,解决方案为:

$(".m-layout-setting").unbind('click').click(function(){
//此处填写逻辑代码
})

------

因为利用js在页面加载后添加需要点击事件的代码,发现在点击后会代码会执行两次,因为有toggle效果,导致弹窗出现又很快丢失

查了一些资料,发现这是冒泡的原因,需要在点击事件代码中加入阻止冒泡的方法

e.stopPropagation();

但是发现还是不行

后面查到,off函数可以解除由on函数所绑定的事件所以在js代码中on函数前调用下Off函数,就正常了

$("li.taskli").off('click','a').on('click','a',function(e){ //在on绑定前调用off去除绑定
//$(document).on('click','li.taskli a',function(e) { //原先的写法
console.log("here")
if ($(this).parent().find('div.popover').size()>0)
{
$(this).popover('destroy')
}else{ 
var uuid = $(this).attr('targetuuid');
var taskhtml = '<div >;
$(this).popover({
placement:'bottom',
title:uuid,
html:'true',
content:taskhtml
}).popover('toggle');

getResultFromFile(uuid)
}
e.stopPropagation(); //阻止冒泡
})

解决jquery绑定click事件出现点击一次执行两次问题

问题定位:通过浏览器F12定位到点击一次出现两次调用。

问题复现:

$("#mail_span").on("click",function(){
        if($(".treeselect").children(".treeselect-up").css("display")=="none"){
            treeSelectClick();
            var $up = $(".treeselect").find(".treeselect-up");
            $up.css({
                display : "block"
            });
            $("#mail_bottom").attr("class", "glyphicon glyphicon-triangle-top");
        }else{
            treeSelectClick();
            $("#mail_bottom").attr("class", "glyphicon glyphicon-triangle-bottom");
        }
    }
})

问题解决:

$("#mail_span").on("click",function(e){
    if(!e.isPropagationStopped()){//确定stopPropagation是否被调用过
        if($(".treeselect1").children(".treeselect-up").css("display")=="none"){
            treeSelectClick();
            var $up = $(".treeselect1").find(".treeselect-up");
            $up.css({
                display : "block"
            });
            $("#mail_bottom").attr("class", "glyphicon glyphicon-triangle-top");
        }else{
            treeSelectClick();
            $("#mail_bottom").attr("class", "glyphicon glyphicon-triangle-bottom");
        }
    }
    e.stopPropagation();//必须要,不然e.isPropagationStopped()无法判断stopPropagation是否调用过
})

查阅资料:

event.preventDefault() :阻止默认行为,可以用 event.isDefaultPrevented() 来确定preventDefault是否被调用过了

event.stopPropagation() :阻止事件冒泡,事件是可以冒泡的,为防止事件冒泡到DOM树上,不触发任何前辈元素上的事件处理函数,可以用 event.isPropagationStopped() 来确定stopPropagation是否被调用过了