jQuery beforeunload不显示消息 [英] jquery beforeunload does not display message
问题描述
用于此目的的jsfiddle位于 http://jsfiddle.net/whDm6/18/
The jsfiddle for this is at http://jsfiddle.net/whDm6/18/
如果在以下代码中取消注释警报,请更改表单值并刷新页面,它将显示警报.所以我知道代码可以执行到这一点.但是,如果我将警报保留为注释状态,它不会像我期望的那样显示beforeunload框.
If I uncomment the Alert in the following code, change a form value, and refresh the page, it displays an alert. So I know the code is executing up to that point. But if I leave the Alert commented out it does not display the beforeunload box like I expect it to.
我尝试过使用bind和基本的window.onbeforeunload = function(){},但未将其与Jquery绑定,但没有一个起作用.
I have tried using bind and also using a basic window.onbeforeunload = function() {} without binding it with Jquery but none of those worked.
使用Jquery 1.8.2
Using Jquery 1.8.2
var currentUlValues = {};
currentUlValues['input1'] = "red";
currentUlValues['input2'] = "blue";
needToConfirm = true;
$(window).on('beforeunload', function(){
if (needToConfirm) {
$.each(currentUlValues, function(key, value) {
var elem = $("#"+key).val();
if (typeof elem !== 'undefined') {
if (elem != currentUlValues[key]) {
//alert(elem + " - " + currentUlValues[key]);
return 'Are you sure you want to leave?';
}
}
});
}
});
HTML表单
<form>
<input id="input1" name="input1" type="text" value="red" />
<input id="input2" name="input2" type="text" value="blue" />
</form>
推荐答案
您是从.each
的回调函数返回的,该回调函数的作用域不正确,您应该在其外部返回字符串.
You are return form the callback function of .each
, which is in wrong scope, you should return the string outside it.
$(window).on('beforeunload', function(){
var is_return = false;
if (needToConfirm) {
$.each(currentUlValues, function(key, value) {
var elem = $("#"+key).val();
if (typeof elem !== 'undefined') {
if (elem != currentUlValues[key]) {
is_return = true;
// here return false is to stop the iterate
return false;
}
}
});
if (is_return) {
return 'Are you sure you want to leave?';
}
}
});
这篇关于jQuery beforeunload不显示消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!