2 回答

TA贡献1827条经验 获得超4个赞
也许这会有所帮助。我相信你已经把这件事复杂化了一点。我在代码中提供了注释供您查看。
注意:我没有使用,moment.js
因为它对你的任务来说是不必要的。
你需要:
来自 Date 对象的时间
单击时将更改的时区参考
将发布时间的间隔(随着 TZ 的变化)
放置输出的地方
// place to put the output
const output = document.getElementById('output');
// starting timezone
var tz = 'America/New_York';
// Capture click event on the UL (not the li)
document.getElementsByTagName('UL')[0].addEventListener('click', changeTZ);
function changeTZ(e) {
// e.target is the LI that was clicked upon
tz = e.target.innerText;
// toggle highlighted selection
this.querySelectorAll('li').forEach(el=>el.classList.remove('selected'));
e.target.classList.add('selected');
}
// set the output to the time based upon the changing TZ
// Since this is an entire datetime, remove the date with split()[1] and trim it
setInterval(() => {
output.textContent = new Date(Date.now()).toLocaleString('en-US', {timeZone: `${tz}`}).split(',')[1].trim();
}, 1000);
.selected {
background-color: lightblue;
}
<div>
<ul>
<li class="selected">America/New_York</li>
<li>America/Chicago</li>
<li>America/Los_Angeles</li>
</ul>
<div id="output"></div>
</div>

TA贡献1812条经验 获得超5个赞
将您的 setInterval 分配给一个变量并在用户选择新值表单下拉列表时清除它并使用新值重新开始间隔
var interval = setInterval(updateTime, 1000);
if(oldValue !== newValue){
clearInterval(interval)
}
添加回答
举报