确认在第一次点击后不起作用:确认不是一个功能

confirm not working after first click: confirm is not a function

我有这个 jQuery 代码,当用户单击 div 中的任何 link 时,它会弹出确认框。但是如果我首先点击link确认框,它会弹出,如果我点击取消操作被取消并且console.log说confirm is not a function如果我点击确定操作被执行console.log 也显示 confirm is not a function 然后如果我再次单击 link 确认框不会再次弹出,直到我重新加载页面。

请问有人知道我哪里错了吗?

$("#aye a").click(function() {
  str = "Removing this Photo, It can not be reversed\nAre You sure You want to remove it?";
  confirm = confirm(str);
  if (confirm) {
    $("#div").html("deleted");
  }
});
<div id="aye">
  <a href="javascript:;">link 1</a>
  <a href="javascript:;">link 2</a>
  <a href="javascript:;">link 3</a>
  <a href="javascript:;">link 4</a>
</div>
<div id="div"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>

View on jsFiddle

您正在使用名为 confirm 的全局变量跟踪 window.confirm

这是一种解决方案,我将您的局部变量称为 confirm2

$("#aye a").click(function(){
    var str = "Removing this Photo, It can not be reversed\nAre You sure You want to remove it?";
    var confirm2 = confirm(str);
    if(confirm2){
        $("#div").html("deleted");
    }
});

请注意,我还添加了 var 关键字以防止这些变量泄漏到全局 space。

$("#aye a").click(function(){
    if(confirm( "Removing this Photo, It can not be reversed\nAre You sure You want to remove it?"))
    {
        // Add class to deleted item and remove click event so user cannot click again
        $(this).addClass("deleted").off("click");
  $("#div").html("deleted");
 }
});
a.deleted{
  color  : silver;
  cursor : not-allowed
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="aye">
   <a href="javascript:;">link 1</a>
   <a href="javascript:;">link 2</a>
   <a href="javascript:;">link 3</a>
   <a href="javascript:;">link 4</a>
</div>
<div id="div"></div>