CodeIgniter中按钮点击启动24小时计时器并显示的问题求助
Hey there! Let's break down the problems with your current code and get that 24-hour timer working when you click the button. Since you're new to JavaScript but have PHP experience, I'll keep this clear and focused on the key issues:
First, the Core Problems
- Your
start()function isn't accessible to the button: Right now,startis wrapped insidejQuery(function start($) { ... }), which means it only exists within that callback's scope—your button'sonclickcan't find it. - Your PHP button isn't rendering: The HTML string in your
ifstatement isn't being echoed out, so the button doesn't even show up on the page!
Updated, Working Code Example
1. Adjust the Timer Script for Global Access
Rewrite your JavaScript so the start() function is available globally, and tweak the timer logic to handle completion cleanly:
<script> // Keep your Timer logic but make it reusable function Timer(duration, display) { let timer = duration; let hours, minutes, seconds; // Store the interval ID so we can stop it later this.interval = setInterval(() => { hours = parseInt((timer / 3600) % 24, 10); minutes = parseInt((timer / 60) % 60, 10); seconds = parseInt(timer % 60, 10); // Add leading zeros for formatting hours = hours < 10 ? `0${hours}` : hours; minutes = minutes < 10 ? `0${minutes}` : minutes; seconds = seconds < 10 ? `0${seconds}` : seconds; display.text(`${hours}:${minutes}:${seconds}`); // Stop the timer when it hits zero (and add DB update later) if (--timer < 0) { clearInterval(this.interval); // Here's where you'll add AJAX to update your database later } }, 1000); } // Move start() to the global scope so your button can call it function start() { const twentyFourHours = 24 * 60 * 60; const display = $('#remainingTime'); // Start the timer new Timer(twentyFourHours, display); } </script>
2. Fix the PHP Button Rendering
Your PHP code wasn't outputting the button—add echo or use alternative PHP syntax for clarity:
<?php if ($provinces['nation_name'] === ""): ?> <center><button onclick="start()">Start Nation</button></center> <?php endif; ?>
Or if you prefer your original syntax:
<? if ($provinces['nation_name'] == "") { echo '<center><button onclick="start()">Start Nation</button></center>'; } ?>
3. Add a Display Element for the Timer
Don't forget to add an element where the timer will show up—otherwise, you won't see the countdown:
<div id="remainingTime">24:00:00</div>
Quick Extra Tips
- To prevent multiple timers from running if the button is clicked again, you can disable the button once it's clicked, or add a check to see if a timer is already active.
- For the database update when the timer finishes, you'll use jQuery's
$.ajax()method to send a request to a CodeIgniter controller method that handles the database update.
内容的提问来源于stack exchange,提问作者user13999169
相关产品推荐
相关产品推荐

