简体   繁体   English

刷新页面时的JavaScript / PHP弹出窗口

[英]JavaScript/PHP Popup when Refreshing Page

I have the following code: 我有以下代码:

<script>
    var myEvent = window.attachEvent || window.addEventListener;
    var chkevent = window.attachEvent ? 'onbeforeunload' : 'beforeunload';

    myEvent(chkevent, function(e) {
        var confirmationMessage = 'HELLO';
        (e || window.event).returnValue = confirmationMessage;
        return confirmationMessage;
    });
</script>

Which runs a small pop up box when the user trys to refresh the page the script is running on. 当用户尝试刷新运行脚本的页面时,它将运行一个小的弹出框。

However, how can I prevent it from running the pop up if they click the Submit button? 但是,如果他们单击“提交”按钮,如何防止其运行弹出窗口?

This should work. 这应该工作。 Note that you have to refresh the snippet for your message to appear, but not when you click the button. 请注意,您必须刷新代码段以使您的消息显示出来,但不必单击按钮时就可以。

 var myEvent = window.attachEvent || window.addEventListener; var chkevent = window.attachEvent ? 'onbeforeunload' : 'beforeunload'; var unloading = true; myEvent(chkevent, function(e) { if(!unloading) return; var confirmationMessage = 'HELLO'; (e || window.event).returnValue = confirmationMessage; return confirmationMessage; }); document.getElementById('submit').addEventListener('click', function(e){ unloading = false; // Because this button does nothing, the reload will load an empty page in SO // However, note there is no beforeunload event actioned. location.reload(); }); document.write('Current Time: ' + Date.now()) 
 <input type="button" value="SUBMIT" id="submit" /> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM