用户关闭浏览器或导航到其他页面时显示消息

时间:2014-02-19 07:40:37

标签: javascript jquery html

我在网页上收集评论,我想要以下功能:

如果用户已进入审核并关闭窗口,那么他们应该收到消息。

如果用户未输入评论,则在关闭窗口时不应收到消息

JavaScript代码:

  function WinClose()
  {
    if(document.getElementById('txtReviewDesc').value == '')
        return 'true';
    else
        return 'false';
  }
  window.onbeforeunload = WinClose;

Html Elements

 <input type="text" id="txtReviewTitle" maxlength="200" autofocus />
 <textarea id="txtReviewDesc" ></textarea>
每当我关闭窗口时,我都会给出消息。我只想在文本框中写一些内容时才想要留言

3 个答案:

答案 0 :(得分:1)

尝试用以下代码替换您的功能:

function WinClose() {
    if(document.getElementById('txtReviewDesc').value != '') {
      return 'Are you sure you want to leave?';
    }
}

另见此文档:https://developer.mozilla.org/en-US/docs/Web/API/Window.onbeforeunload

答案 1 :(得分:0)

return 'true';更改为return true,不加引号。对return false执行相同的操作。

答案 2 :(得分:0)

您的代码有效。

检查这个小提琴:http://jsfiddle.net/shyamchandranmec/CYk8S/

<input type="text" id="txtReviewTitle" maxlength="200" autofocus />
<input id="txtReviewDesc" />

我已将您的返回类型从'true''false'更改为true和false