技术需求:页面加载后30秒内点击按钮弹出致歉提示,超时不触发
Solution for 30-Second Click Trigger Requirement
Got it, let's tweak the code to match your exact needs: we want the "We are sorry" alert to only pop up when the button is clicked within 30 seconds of page load, and do absolutely nothing if clicked after 31 seconds or more.
Here's the revised, working code:
<button class="btn waves-effect waves-light" type="submit" name="action" id="popupBoxAccept"> Submit <i class="material-icons right">send</i> </button> <script> // Flag to track if the button can still trigger the alert let isAlertEnabled = true; // Set a timer to disable the alert after 30 seconds (30000 milliseconds) setTimeout(() => { isAlertEnabled = false; }, 30000); // Attach click event listener to the button document.getElementById('popupBoxAccept').addEventListener('click', function(e) { // Optional: Stop form submission if you don't want the form to submit (adjust based on your use case) e.preventDefault(); // Only show the alert if we're still within the 30-second window if (isAlertEnabled) { alert('We are sorry'); } }); </script>
Breakdown of the Logic:
isAlertEnabledflag: This simple variable acts as a gatekeeper. It starts astrue(allowing the alert) and switches tofalseonce the 30-second timer runs out.- 30-second timer: The
setTimeoutfunction waits exactly 30 seconds, then flips the flag to disable future alert triggers. - Click handler: When the button is clicked, we first check if the flag is still
true. If yes, we show the alert; if not, the code does nothing—no alert, no extra actions.
If you prefer using jQuery (since your original code used it), here's the jQuery version:
<button class="btn waves-effect waves-light" type="submit" name="action" id="popupBoxAccept"> Submit <i class="material-icons right">send</i> </button> <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> <script> let isAlertEnabled = true; setTimeout(() => { isAlertEnabled = false; }, 30000); $('#popupBoxAccept').click(function(e) { e.preventDefault(); if (isAlertEnabled) { alert('We are sorry'); } }); </script>
内容的提问来源于stack exchange,提问作者Jonas Palačionis
相关产品推荐
相关产品推荐

