First I used window.onbeforeunload
on my application. It's working on over page but when click on anchor link it should be disabled <a href="abc.com">Click</a>
. Any ideas? Please share. My code is below it is not working:
var submitFormOkay = false;
window.onbeforeunload = function () {
if (!submitFormOkay) {
return "Don't delay your Success. Get FREE career counselling session. Fill in the details below";
} else {
submitFormOkay = '';
}
}
<a class="navbar-brand" href="http://www.google.com">Click</a>
答案 0 :(得分:1)
您可以在document.body
上附加全局点击处理程序,如果点击通过a
元素,则将submitFormOkay
设置为true
(或者您可以使用其他变量绕过检查,或只是通过将null
分配给window.onbeforeunload
来清除处理程序,例如:
$(document.body).on("click", "a", function() {
submitFormOkay = true; // Or set another flag you'll check,
// or clear onbeforeunload entirely
});
没有jQuery(因为我最初错过了jquery
标签):
document.body.addEventListener("click", function(e) {
var element;
for (element = e.target; element != document.body; element = element.parentNode) {
if (element.tagName.toUpperCase() === "A") {
submitFormOkay = true; // Or set another flag you'll check,
// or clear onbeforeunload entirely
break;
}
}
}, false);
答案 1 :(得分:-2)
使用jquery可以遵循:
var submitFormOkay = false;
$(window).on('beforeunload',function () {
if (!submitFormOkay) {`enter code here`
return "Don't delay your Success. Get FREE career counselling session. Fill in the details below";
} else {
submitFormOkay = '';
}
})
<a class="navbar-brand" href="http://www.google.com">Click</a>
$('a').on('click',function(e){
e.preventDefault();
$(window).off('beforeunload');
window.location = $(this).attr('href');
});