javascript - onbeforeunload 使用 location.href 进行导航

标签 javascript jquery html

我的应用程序是MVC5,我想在用户关闭浏览器选项卡时提醒他们。 我找到了这个解决方案Setting onbeforeunload on body element in Chrome and IE using jQuery ,效果很好,除了我在少数情况下使用 location.href (Telerik 网格内的自定义命令按钮)。 尝试了以下方法:

 $(window).bind('hashchange', function() {
              validNavigation = true;
    }); 

避免询问用户是否要离开页面。 有没有更好的方法在关闭浏览器选项卡之前提醒用户?

最佳答案

试试这个;)

需要对此代码进行一些修改:

window.onbeforeunload = function() {
  if(validNavigation){
    validNavigation = false;
    /* if this click is valid means user action is not close window or reload page then just return; */
    return;
  }

  /* Want to ask user before leaving the page */
  return "Are you sure you want to leave this page bla bla bla?"; // you can make this dynamic, ofcourse...
};


validNavigation = true;
$(document).on('click', '.validNavigation', function(){
  validNavigation = true;
});

现在您需要做的是将 validNavigation 类添加到您不想向用户显示 onbeforeunload 消息的所有链接;

更新根据评论:

function gotopage(args){
  /* set validNavigation to true to don't show warning on page load; */
  validNavigation = true;
  window.location.href = [args];
}

对于您不想向用户显示警告的操作,只需设置 validNavigation = true; 并在其后面放置语句可能会导致位置更改;

关于javascript - onbeforeunload 使用 location.href 进行导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36687168/

相关文章:

html - 如何为一个div设置垂直居中对齐另一个div

javascript - 使用 $(this) 不起作用

javascript - 防止客户端存储 XMLHttpRequest 文档

javascript - jQuery - 仅在前景元素上调用 .click()?

javascript - 如何检查div是否有元素innerHTML

javascript - 扫雷板的cell不出现Html&CSS&JS

javascript - 如何将行索引值附加到 td 的 ID

javascript - 如何将 Node.js 二进制流从 zip 写入 S3

javascript - .选中复选框时加载内容,未选中时删除内容

jquery - 左键单击 + 按住 = 添加复选框