Javascript 检查卸载前是否保存了更改
我有以下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
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;
}