0

我在我的网站中添加了一个机制,该机制应该在用户即将关闭他们正在使用的页面时警告用户。我将一个函数绑定dropDraftConfirmationwindow.onbeforeunload事件,如下所示:

window.onbeforeunload = dropDraftConfirmation;

function dropDraftConfirmation()
{
    if (<there is an input or textarea element not empty on the page>) {
        alert('Your changes will be lost. Are you sure you want to exit the page?');
    }
}

但是每次我关闭页面时都会调用它。所以我的问题是,如何检测页面中是否有空的 input 或 textarea 元素?顺便说一句,我正在使用jQuery

4

4 回答 4

2

我认为这应该可以解决问题。

window.onbeforeunload = dropDraftConfirmation;

function dropDraftConfirmation()
{
    if ($("input:empty,textarea:empty").length == 0) {
        alert('Your changes will be lost. Are you sure you want to exit the page?');
    }
}
于 2012-12-07T06:40:04.417 回答
0

像下面这样重写您的函数,以在卸载之前检查任何未保存的更改

window.onbeforeunload = checkUnSaved;

function checkUnSaved(){
     if($("#textarea").val() === ""){
         dropDraftConfirmation();
     }else
         return;
}

function dropDraftConfirmation()
{
    if (<there is an input or textarea element not empty on the page>) {
        alert('Your changes will be lost. Are you sure you want to exit the page?');
    }
}
于 2012-12-07T06:38:49.693 回答
0

您还可以执行以下操作:

var errors = 0;

    $("input, textarea").map(function(){
        var val = $.trim( $(this).val() );
        if( val.length < 1 ) {
           errors++;  
        }
    });

    if( errors > 0 ) {
        alert('Your changes will be lost. Are you sure you want to exit the page?');
    }
于 2012-12-07T06:47:51.073 回答
0

您的情况将如下所示:

if ($("input[value!='']").length > 0 || $('textarea:not(:empty)').length > 0 ){
于 2012-12-07T06:50:25.283 回答