简体   繁体   English

onbeforeunload功能无法正常工作

[英]onbeforeunload function not working properly

 $(function(){
   var a=document.getElementById('text_editor_textarea'),regEx=/^\s*$/,
 updateOrig = function() {
       var sc = $(a).data('sceditor');
         if(sc){
         sc.bind('keypress', sc.updateOriginal);
         sc.blur(sc.updateOriginal);
   }else {
     setTimeout(updateOrig , 200);
   }
 };
 updateOrig();  
 if(a.value !== "" && regEx.test(a.value) ){
       window.onbeforeunload = function(){
         return "You have a post waiting to be submitted";
      };
  }
});

This code should check if there is data in a and if there is onbeforeunload the alert should be prompted. 此代码应检查是否有数据在a ,如果有onbeforeunload警报应提示。 It works except that even if there is no data in the textarea it still is prompted. 它起作用,除了即使文本区域中没有数据之外,仍然会提示您。 Am I doing something wrong here? 我在这里做错什么了吗?

Just do a.value !== "" instead of a.value !== null || a.value !== "" 只需执行a.value !== ""而不是a.value !== null || a.value !== "" a.value !== null || a.value !== "" inside of this if block: if块内的a.value !== null || a.value !== ""

if (a.value !== null || a.value !== "") {
    window.onbeforeunload = function () {
        return "You have a post waiting to be submitted";
    };
}

Also, flip the if and the event function assignment to this: 另外,将if和event函数分配给它:

window.onbeforeunload = function () {
    if (a.value !== "") {
        return "You have a post waiting to be submitted";
    }
};

I didn't realize this before, but only on page load would your message get called since otherwise the assignment wouldn't occur since the textarea would be empty when you first opened the page. 我以前没有意识到这一点,但是只有在页面加载时才会调用您的消息,因为否则在第一次打开页面时textarea将为空,因此不会进行分配。

jsFiddle jsFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM