除了提交表单外,阻止用户离开网页

ing*_*.am 8 html javascript jquery user-input user-experience

要阻止用户离开我的页面,我正在使用此javascript:

window.onbeforeunload = function()
{
  if($('textarea#usermessage').val() != '')
  {
    return "You have started writing a message.";
  }
};
Run Code Online (Sandbox Code Playgroud)

这会显示一条消息,警告用户不要离开页面,因为他们已经开始编写邮件但未提交.这表明可以防止用户丢失此数据.

现在,如何在提交表单时停止显示此消息?

arc*_*hil 9

function handleWindowLeaving(message, form) {
    $(window).bind('beforeunload', function (event) {
        return message;
    });
    $(form).bind('submit', function () {
        $(window).unbind('beforeunload');
    });
};
Run Code Online (Sandbox Code Playgroud)

在调用它时,传递您的消息和表单引用,它将在提交表单时自动删除onbeforeunload.否则,向用户显示消息


Pis*_*3.0 5

在表单的提交处理程序中设置一个标志; 检查是否在卸载处理程序中设置了标志.如果是 - 瞧,这是表格提交!