我在我的网站中添加了一个机制,当用户即将关闭他们正在使用的页面时,它应该警告用户。我正在将函数dropDraftConfirmation
绑定到window.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?');
}
}
但每次关闭页面时都会调用此方法。所以我的问题是,如何检测页面中是否有不为空的输入或textarea元素?顺便说一句,我正在使用jQuery。
答案 0 :(得分: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?');
}
}
答案 1 :(得分: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?');
}
}
答案 2 :(得分: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?');
}
答案 3 :(得分:0)
您的情况将如下所示:
if ($("input[value!='']").length > 0 || $('textarea:not(:empty)').length > 0 ){