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

});

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM