2

这已经被问过了,我知道,但我不明白为什么这对我不起作用。

http://jsfiddle.net/M9tnP/16/

尝试检测表单更改,如果用户尝试离开,我希望他们确认他们将丢失更改...

var dirty = false;
$("form#add_item :input").change(function() {
    dirty = true;
});

$("window").on('beforeunload', function() {
    if (dirty) {
        return 'You have unsaved changes! If you leave this page, your changes will be lost.';
    }

});​</p>

4

2 回答 2

7

You need to set the event handler for onbeforeunload directly on the window object:

var dirty = false;
$("form#add_item :input").change(function() {
    //alert("form changed!")
    dirty = true;
});

window.onbeforeunload = function() {
    if (dirty) {
        return 'You have unsaved changes! If you leave this page, your changes will be lost.';
    }
};​

Working example: http://jsfiddle.net/M9tnP/20/

于 2012-09-26T18:43:50.420 回答
0

你需要:

$(window).on('beforeunload', function() {...})

, 不是:

$("window").on('beforeunload', function() {...})

(周围没有引号window)。将javascript 变量$(window)包装在一个 jQuery 对象中,其中选择页面上的所有标签,其中正好有 0 个。window$("window")<window>

(大多数时候。事实上你可以这样做$('body').append('<window></window>'),然后$("window")匹配那个新标签——但不要那样做。)

于 2013-08-08T21:12:06.217 回答