我是一名很少使用 Javascript 的 PHP 程序员,因此我需要帮助弄清楚如何使用 JS 或 JQuery 来完成此任务(我目前有 jquery-1.7.min.js)。我用 PHP 创建了三个时钟来显示不同时区的时间,我想使用 JS 每分钟增加时间。
时钟的 HTML 是这样的:
<div class="clock">
<div class="pm"></div>
<div class="time">11:59</div>
</div>
添加一分钟后应该是这样的:
<div class="clock">
<div class="am"></div>
<div class="time">00:00</div>
</div>
这是我到目前为止所得到的:
var myVar = setInterval(function(){setClocks()},60000);
function setClocks()
{
$(".clock").each(function() {
var ampm = $("div:first-child");
var time = $(".time");
// add one minute to time and toggle am/pm if needed
time.innerHTML = newTime;
}
}
任何帮助将不胜感激。
更新:
感谢 Dead133 和 kei,我已经搞定了。这是我更新的代码:
var myVar = setInterval(function(){setClocks()}, 60000);
function setClocks()
{
$(".clock").each(function() {
var ampm = $("div:first-child", $(this));
var time = $(".time", $(this));
var parts = time.text().split(':');
var hours = parseInt(parts[0], 10);
var minutes = parseInt(parts[1], 10);
++minutes;
if (minutes == 60)
{
minutes = 0;
++hours;
if (hours == 12)
{
ampm.toggleClass('am');
ampm.toggleClass('pm');
}
}
if (hours > 12) hours -= 12;
if (hours.toString().length < 2) hours = "0" + hours;
if (minutes.toString().length < 2) minutes = "0" + minutes;
time.text(hours + ':' + minutes);
})
}
谢谢大家的帮助!我用 PHP 做过这种事情,所以我知道其中的逻辑。只是 JS/JQ 挂了我的电话。
最佳答案
var myVar = setInterval(function(){setClocks()},60000);
function setClocks() {
$(".clock").each(function() {
var ampm = $("div:first-child", $(this)); // $(this) is important since you're dealing with 3 clocks
var time = $(".time", $(this));
var clockTime = time.text().split(':'),
hours = clockTime[0],
minutes = clockTime[1];
++minutes;
if (minutes == 60) {
minutes = 0;
++hours;
if (hours == 12) {
hours = 0;
ampm.toggleClass('am')
.toggleClass('pm');
}
}
if (hours.toString().length < 2) hours = "0"+hours; // Added padding to the digits
if (minutes.toString().length < 2) minutes = "0"+minutes;
time.text(hours + ':' + minutes);
}); // ); is important
}
关于javascript - 添加一分钟到 hh :mm with JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19776620/