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)
}
添加回答
舉報