在卸载之前检查是否保存了更改 [英] check if changes saved before unload

查看:89
本文介绍了在卸载之前检查是否保存了更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下javaScript

I have the following javaScript

编辑:包含的cahngesSaved分配

 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是什么,都会提示消息。

but the message is being prompted regardless of what changesSaved is set too.

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

What actually I actually get is the following:

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

or if changesSaved is set to false it says false instead.

我不能这样做吗?

推荐答案

<body onbeforeunload="return bye()">

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

我就是这样做的。

或纯JavaScript:

or in pure JavaScript:

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

这篇关于在卸载之前检查是否保存了更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆