jquery中click事件重复绑定问题

在最近的项目中遇到这样一个问题:

从心愿单中删除产品,1.如果直接确定删除,则删除成功,2.如果先取消删除,再次点击再确认删除,则会出现问题,测试发现:

对未来元素(类名为deleteFav的对象)绑定click事件中,如果function中还包含有元素(简称A)的click事件,在点击两次删除按钮时会出现A 元素的click事件重复绑定的情况

$("body").on("click",".deleteFav",function(){//点击删除button
  var id=$(this).attr("id");
  $(".alertBtns").append("<span class='cancel' style='margin-left:14px;'>CANCEL</span>");
  $(".alertwindow .tips").html("Are you sure you want to remove this Photo from the favorites? ");
  $(".alertwindow").show();
  $(".alertBtns .conf").click(function(event){

    //alert("test");   //------第二次点击.deleteFav 会发现弹出两次test
    location.href=rootDomain +'/wishlists/delete/'+id;
  });

});

解决方法,先解绑,再绑定

$("body").on("click",".deleteFav",function(){//点击删除button
  var id=$(this).attr("id");
  $(".alertBtns").append("<span class='cancel' style='margin-left:14px;'>CANCEL</span>");
  $(".alertwindow .tips").html("Are you sure you want to remove this Photo from the favorites? ");
  $(".alertwindow").show();
  $(".alertBtns .conf").unbind("click").click(function(event){
    location.href=rootDomain +'/wishlists/delete/'+id;
  });

});

原文地址:https://www.cnblogs.com/sandy-happyhour/p/5316405.html