gpt4 book ai didi

javascript - 单击带有 window.onbeforeunload 的链接时出现问题

转载 作者:行者123 更新时间:2023-12-03 01:52:21 24 4
gpt4 key购买 nike

我有一个父div content_div,其中包含表格内的表单元素,用户可以在其中选择多个行元素(可点击行)、下载链接元素等。

我会弹出一条警告,提示用户已完成更改,然后尝试刷新而不单击“保存”按钮。

当我选择一行并尝试单击该行内的下载链接时,我不需要显示警告弹出窗口。我有以下代码,但它不起作用。

如果我不选择任何行并尝试单击任何下载链接,它不会显示任何弹出窗口,这意味着没问题。

如果我选择任何行,然后尝试单击任何下载链接,它会显示弹出窗口,这在我的情况下是错误的。

如果用户点击我的 #content_div 之外的一些其他链接,它会显示弹出窗口,这对我来说是正确的。

$(function() {
var formmodified = 0;

//click event for each row inside the table
$(".course_row").click(function(e) {
-- -- -
formmodified = 1; //setting the variable to 1 means user
has changed something inside the page
});
//when form submits
$("#submit").click(function() {
formmodified = 0; //assuming that form is saved after form change
});
//function for warning popup
window.onbeforeunload = confirmExit;

function confirmExit() {
var element_clicked = 0;
//#content_div is the main parent which contain the entire
contents.

$('#content_div').children().on('click', function(e) {
console.log('clicked');
element_clicked = 1; //means the clicked element is inside the #content_div which can be a link or other things

});
console.log(element_clicked);
EDIT: I am always getting element_clicked value as 0 when I click any element inside the div.The value 'clicked'
is showing.I dont know why the value
for the variable is not setting to 1


if (element_clicked) {
//element_clicked = false;
return; // abort beforeunload
} else {
if ((!element_clicked) && (formmodified == 1)) {
return "The selected courses are not saved.
Do you wish to leave the page ? ";
}

}

}
});

请在这种情况下帮助我。提前致谢

最佳答案

只需添加 click() 事件到 anchor 元素并取消绑定(bind) onbeforeunload 事件即可。

$("a").on('click', function() {
window.onbeforeunload = null;
});

这只是一个例子。您可以向选择器添加类或 ID,以便仅在单击特定 anchor 标记时取消绑定(bind)事件。

例如

$("#content_div a").on('click', function() {
window.onbeforeunload = null;
});

编辑

如果您想添加 onbeforeunload 进行刷新,您要么必须在触发任何更改时执行此操作,要么只需在按下 F5 按钮时添加事件。

说实话,我认为第一个解决方案更好,因为即使用户单击浏览器中的刷新按钮,弹出窗口也会出现。

所以你必须改变你的功能。

如果你不愿意。这是快速添加到 F5 按钮。

$(document.body).on("keydown", this, function (event) {
if (event.keyCode == 116) {
window.onbeforeunload = true;
}
});

关于javascript - 单击带有 window.onbeforeunload 的链接时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50365841/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com