jquery - 仅使用一项功能显示多个时区
问题描述
我想为不同的国家显示不同的时区。问题是我无法让它像我想要的那样工作。
我有一个名为data-hour
. 这可以是加/减任何数字。在函数中update
,我用var AddHours = $('.hours').data("hours");
.
如果我只想显示一次,我可以简单地使用类似的东西date.setHours(date.getHours() + 3);
,它会显示当前时间 +3 小时。我已将其修改为date.setHours(date.getHours() AddHours);
,但它没有显示任何内容。显然我做错了什么。但是什么?
谢谢你。
代码:
<!--Country One-->
<p id="C_one" class="TextCenter NoMargin ClockUnit">
<span class="hours" data-hours="+4"></span>:<span class="minutes"></span>:<span class="seconds"></span>
</p>
<!--Country Two-->
<p id="C_two" class="TextCenter NoMargin ClockUnit">
<span class="hours" data-hours="-1"></span>:<span class="minutes"></span>:<span class="seconds"></span>
</p>
<!--Country Three-->
<p id="C_three" class="TextCenter NoMargin ClockUnit">
<span class="hours" data-hours="+2"></span>:<span class="minutes"></span>:<span class="seconds"></span>
</p>
<script>
var $hOut = $('.hours'),
$mOut = $('.minutes'),
$sOut = $('.seconds');
function update(){
var AddHours = $('.hours').data("hours");
var date = new Date();
date.setHours(date.getHours() AddHours);
var hours = date.getHours();
hours = (hours < 10 ? "0" : "") + hours;
var minutes = date.getMinutes();
minutes = (minutes < 10 ? "0" : "") + minutes;
var seconds = date.getSeconds();
seconds = (seconds < 10 ? "0" : "") + seconds;
$hOut.text(hours);
$mOut.text(minutes);
$sOut.text(seconds);
}
update();
window.setInterval(update, 1000);
</script>
解决方案
如下更新您的代码。
循环$('.TextCenter')
并在其中找到.hours
, .minutes
, .seconds
。使用$(this).find
.
更新你的date
as date = new Date(date.getTime() + (AddHours * 60 * 60 * 1000));
。
function update() {
$('.TextCenter').each(function() {
var $hOut = $(this).find('.hours'),
$mOut = $(this).find('.minutes'),
$sOut = $(this).find('.seconds');
var AddHours = $hOut.data("hours");
var date = new Date();
date = new Date(date.getTime() + (AddHours * 60 * 60 * 1000));
//date.setHours(date.getHours());
var hours = date.getHours();
hours = (hours < 10 ? "0" : "") + hours;
var minutes = date.getMinutes();
minutes = (minutes < 10 ? "0" : "") + minutes;
var seconds = date.getSeconds();
seconds = (seconds < 10 ? "0" : "") + seconds;
$hOut.text(hours);
$mOut.text(minutes);
$sOut.text(seconds);
});
}
update();
window.setInterval(update, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<!--Country One-->
<p id="C_one" class="TextCenter NoMargin ClockUnit">
<span class="hours" data-hours="+4"></span>:<span class="minutes"></span>:<span class="seconds"></span>
</p>
<!--Country Two-->
<p id="C_two" class="TextCenter NoMargin ClockUnit">
<span class="hours" data-hours="-1"></span>:<span class="minutes"></span>:<span class="seconds"></span>
</p>
<!--Country Three-->
<p id="C_three" class="TextCenter NoMargin ClockUnit">
<span class="hours" data-hours="+2"></span>:<span class="minutes"></span>:<span class="seconds"></span>
</p>