问题描述
我正在尝试在用户关闭浏览器/选项卡时显示一条确认消息,而在单击页面上的任何链接时不显示该消息.
I am trying to display a confirmation message when the user closes the browser/tab and not when any of the links on page is clicked.
我已经在窗口关闭上显示消息的第一部分工作正常,但是问题是当用户单击页面上的任何链接时,也会显示消息/警报.
I have got the first part of displaying the message on window close working nicely but problem is that the message/alert is displayed also when user clicks on any link on the page.
我从某处获得了代码来防止这种行为,但是无论何时单击任何链接,都会弹出警报.
I have got code from somewhere to prevent this behavior but still when ever any link is clicked the alert pops up.
这是代码:
<script src="js/jquery-1.7.1.min.js"></script>
<script src="js/jquery-ui.min.js"></script>
<script type="text/javascript" src="js/backfix-min.js"></script>
$(document).ready(function() {
$(window).bind('beforeunload', function(e){
$("#lead-gen-modal").dialog("open");
// This line only appears in alert boxes for IE
return "Wait\! Don\'t Go\! We have a special offer for you\. Stay on this page to receive big savings\!";
});
$("a").click(function() {
window.onbeforeunload=null;
});
});
推荐答案
只需使用全局变量并在单击链接时将其设置为false
.
just use a global variableand set it to false
when clicking a link.
var key = true;
$(window).bind('beforeunload', function(e){
if(key)
$("#lead-gen-modal").dialog("open");
});
更新:
$(document).on("click","a",function() {
key=false;
});
或者如果您只想防止关闭窗口,则可以执行以下操作:
or if you just want to prevent closing window you can do this :
window.onbeforeunload = function(e){
if(key)
return false;
}
这篇关于jQuery仅在关闭窗口时显示弹出窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!