Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/462.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 检查卸载前是否保存了更改_Javascript_Dom Events_Onbeforeunload_Onunload - Fatal编程技术网

Javascript 检查卸载前是否保存了更改

Javascript 检查卸载前是否保存了更改,javascript,dom-events,onbeforeunload,onunload,Javascript,Dom Events,Onbeforeunload,Onunload,我有以下JavaScript 编辑:已保存更改的已包含作业 var changesSaved = true; $(document).ready(function () { $(".applyChanges").click(function (e) { e.preventDefault(); var id = (this).id; var dayofweek = document.getElem

我有以下JavaScript

编辑:已保存更改的已包含作业

 var changesSaved = true;

    $(document).ready(function () {

        $(".applyChanges").click(function (e) {
            e.preventDefault();
            var id = (this).id;
            var dayofweek = document.getElementById("dayofweek" + id).value;
            var hour = document.getElementById("hour" + id).value;
            var duration = document.getElementById("duration" + id).value;
            $.ajax({
                url: '@Url.Action("ApplyChanges")',
                type: 'POST',
                data: {
                    id: id,
                    dayofweek: dayofweek,
                    hour: hour,
                    duration: duration
                },
                success: function (data) {
                    $('#Calendar').fullCalendar('refetchEvents')
                    $('#Calendar2').fullCalendar('refetchEvents')
                    changesSaved = false;
                }
            });
        });
    });

window.onbeforeunload = function () {
    if (changesSaved == true) {
        return true;
    } else {
        return ("You havent saved your changes. Are you sure you want to leave the page?")
    }
}
但是无论设置了什么
changesaved
,都会提示消息

事实上,我得到的是:

或者,如果
changesaved
设置为false,则表示false


我不能这样做吗?

您在哪里设置
changesaved
?添加
console.log(changesaved)
并查看函数中的值。有趣的是,我只希望它弹出一个对话框,其中包含
“undefined”
,但似乎在chrome@Esailija-简化代码后,现在就不那么花哨了。(只是开个玩笑)当你点击“取消”时,页面仍在关闭。你只需执行“返回已保存的更改”甚至
返回确认(“…”)
<body onbeforeunload="return bye()">

function bye(){
    if(changesSaved) {
        return "You havent saved your changes."
    }
}
window.onbeforeunload = function() {
    if (changesSaved) {
        return "You haven't saved your changes.";
    }
};
window.onbeforeunload = function () {
     var changesSaved = confirm("You havent saved your changes. Are you sure you want to leave the page?");
    if (changesSaved) {
        return true;
    } else {
        return false;
    }