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

标签 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.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?")
    }
}

但无论设置什么 changesSaved 都会提示该消息。

我实际得到的是以下内容:

enter image description here

或者如果 changesSaved 设置为 false,则改为 false。

我可以不这样做吗?

最佳答案

<body onbeforeunload="return bye()">

function bye(){
    if(changesSaved) {
        return "You havent saved your changes."
    }
}

我就是这么做的。

或者在纯 JavaScript 中:

window.onbeforeunload = function() {
    if (changesSaved) {
        return "You haven't saved your changes.";
    }
};

关于javascript - 检查卸载前是否保存了更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10873546/

相关文章:

javascript - 在 JavaScript 中停止 setInterval 调用

javascript - 使用 onbeforeunload :

javascript - 如何从 PrototypeJS 中的元素获取纯文本?

javascript - 在 React 和 Vanilla Javascript 中输入数字 `e` 时不会调用 onChange

JavaScript、鼠标事件和类

angularjs - 在angularjs中检测页面卸载

javascript - 在 onbeforeunload 事件的窗口确认时调用回调函数

javascript - angular.injector 在每次调用时返回新的服务实例

javascript - 使用 Hammer.js 的事件委托(delegate)

javascript unshift 参数返回意外结果