我在JavaScript中製作了一個秒錶,並且通過HTML的h1標籤顯示它,並且我可以在JS中使用以下代碼獲取它的textContent。使用javascript獲取HTML元素的值
<h1 id="time">00:00:00</h1>
var h1 = document.getElementById('time'),
getTimer = h1.textContent;
這完全取的價值,但問題是,當我打的啓動按鈕,運行秒錶,然後如果點擊的getTime按鈕,它仍取h1標籤的靜態值是00:00:00,這不是我正在尋找的。我想獲取不斷更新的h1標籤的當前值。 假設我點擊開始按鈕,然後10秒後,如果我點擊getTime我想00:00:10作爲getTimer變量的值,但在我的情況下,它只顯示00:00:00。
下面是相同的working codepen演示。
var h1 = document.getElementById('time'),
start = document.getElementById('start'),
stop = document.getElementById('stop'),
clear = document.getElementById('clear'),
seconds = 0, minutes = 0, hours = 0,
t,
\t \t getTimer = document.getElementById('time').textContent,
\t \t fetchVal = document.getElementById('fetchVal'),
\t \t form = document.getElementById('form');
function add() {
seconds++;
if (seconds >= 60) {
seconds = 0;
minutes++;
if (minutes >= 60) {
minutes = 0;
hours++;
}
}
h1.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);
timer();
}
function timer() {
t = setTimeout(add, 1000);
}
/* Start button */
start.onclick = timer;
/* Stop button */
stop.onclick = function() {
clearTimeout(t);
}
/* Clear button */
clear.onclick = function() {
h1.textContent = "00:00:00";
seconds = 0; minutes = 0; hours = 0;
}
form.addEventListener('submit', function(e){
\t e.preventDefault();
alert(getTimer);
});
<form action="#" id="form">
\t <h1 id="time">00:00:00</h1>
<button id="start">start</button>
<button id="stop">stop</button>
<button id="clear">clear</button>
<button type="submit" id="fetchVal">Get Time</button>
</form>
我怎麼h1標籤的當前值?我正在尋找純JS的解決方案
在此先感謝您的幫助。
'getTimer =的document.getElementById( '時間')textContent'是你的網頁加載值'00:00:00',所以總是會得到該值!應改變'getTimer = document.getElementById('time')'和alert(getTimer.textContent' –