在窗口中单击按钮完成之前,光标不会停止.请继续卸载

cursor not stopping until button click completes in window.onbeforeunload?

本文关键字:光标 卸载 继续 单击 窗口 按钮      更新时间:2023-09-26

我有下面的window.onbeforeunload的javascript代码。当按下浏览器返回按钮时,我正在调用代码隐藏按钮点击方法。

现在的问题是,直到$("#buttonclientid").click()完成,光标才停止。只是调用该方法并转到下一个语句。如何按住或停止光标直到$("#buttonclientid").click()完成,然后移动到下一步?

var form_has_been_modified = 0;
  $(function () {
      $("input").keyup(function () {
          form_has_been_modified = 1;
      })
      window.onbeforeunload = function (e) {
          if (!form_has_been_modified) {
                  return;
          }
                doYouWantTo();
      }
   });
   function doYouWantTo(){
        doIt=confirm('Do you want to save the data before leave the page?');
        if (doIt) {
             var returnbutton;
             //cursor should stop here until click function completes.
             returnbutton = $("#buttonclientid").click();
        }
        else{
            }
        }

我认为您的问题在于doYouWantTo函数没有返回要传递回onbeforeunload的值,因此它在运行函数的同时离开页面,而不是等到它完成。

你在这里最好的行动是:

return doYouWantTo()
....
if(doIt) {
    $('#buttonclientid').click(function() { // unsure if you can attach callback to click but idea is same
        return true;
    });
} else {
    return true;
}

将事件处理程序绑定到onbeforeunload事件时,它应该返回以下两项之一:

  • 如果希望显示确认,则处理程序应返回一个字符串
  • 如果您不希望显示确认(跳过处理程序),则返回undefined(或者根本不返回,效果相同)

话虽如此,你的代码应该是这样的:

var form_has_been_modified = false;
$("input").keyup(function () {
    form_has_been_modified = true; // use a boolean :P
});
window.onbeforeunload = function (e) {
    if (form_has_been_modified) {
        return 'Do you want to save the data before leave the page?';
    } else {
        return undefined; // this can be omitted if you prefer
    }
};

告诉用户在系统对话框上单击了什么的唯一方法是使用setTimeout。有关该主题的详细信息,请参阅此问题。