Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/367.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript确认对话框在取消事件时继续重新生成_Javascript_Jquery_Html - Fatal编程技术网

JavaScript确认对话框在取消事件时继续重新生成

JavaScript确认对话框在取消事件时继续重新生成,javascript,jquery,html,Javascript,Jquery,Html,场景:我只想在窗口更改时警告用户;所以我使用了jQuery的窗口模糊和JavaScript的确认对话框。当用户单击“确定”按钮时,应用程序将重定向到另一个页面&当用户单击“取消”按钮时,不会发生任何事情。他可以在同一页上继续他的工作 问题:确定按钮工作正常,但当我单击取消按钮时,浏览器会继续重新生成对话框。我怎样才能阻止它 代码: $(window).blur( function (e) { var closeWindow = window.confirm("Your test

场景:我只想在窗口更改时警告用户;所以我使用了jQuery的窗口模糊和JavaScript的确认对话框。当用户单击“确定”按钮时,应用程序将重定向到另一个页面&当用户单击“取消”按钮时,不会发生任何事情。他可以在同一页上继续他的工作

问题:确定按钮工作正常,但当我单击取消按钮时,浏览器会继续重新生成对话框。我怎样才能阻止它

代码

$(window).blur( function (e) {

        var closeWindow = window.confirm("Your test will be cancelled if you switch the tabs.");

        if (closeWindow) {

            // redirect to another page

        }
        else {

            // do nothing.
        }
});

正如@ROAL所解释的,第一个模糊事件是因为实际的模糊,其余的是因为浏览器试图从选项卡移开。一个简单的解决方案是使用一个标志来区分用户生成的事件和浏览器生成的事件。尝试一下:

var manualCancellation = false;
$(window).blur( function (e) {
    if(!manualCancellation ){

      var closeWindow = window.confirm("Your test will be cancelled if you switch the tabs.");
      console.log(e);
      if (closeWindow) {

          // redirect to another page

      }
      else {
          manualCancellation = true;
          // do nothing.
      }
    } else {
        // Reset the value of manualCancellation so that the event is fired the next time.
      manualCancellation = false;

    }
});

用户单击另一个选项卡,导致触发
blur
事件,但在浏览器试图更改选项卡之前,它会被
confirm
对话框停止。用户取消后,浏览器继续尝试更改选项卡,触发
blur
事件并再次中断。。。这种情况可能会一直持续下去(刚刚在Chrome58上进行了测试)。