document.write
是問題所在。它只在瀏覽器完成加載頁面之前運行。之後,document.write
不起作用。它只是刪除所有現有的頁面內容。
您的第一個document.write
在頁面完全加載之前執行。這就是爲什麼你應該看到兩個按鈕旁邊的0
。
然而,頁面已加載。點擊一個按鈕會導致事件處理程序被執行,所以document.write
將被調用,這在當時不起作用,因爲頁面已經完全加載。
document.write
不應該再使用了。有許多更新DOM的現代方法。在這種情況下,它會創建一個<span>
元素並使用textContent
更新其內容。
此外,使用addEventListener
而非內聯事件監聽器:
var x = 0;
var span = document.querySelector('span'); // find the <span> element in the DOM
var increment = document.getElementById('increment'); // find the element with the ID 'increment'
var decrement = document.getElementById('decrement'); // find the element with the ID 'decrement'
increment.addEventListener('click', function() {
// this function is executed whenever the user clicks the increment button
span.textContent = x++;
});
decrement.addEventListener('click', function() {
// this function is executed whenever the user clicks the decrement button
span.textContent = x--;
});
<button id="increment">increment</button>
<button id="decrement">decrement</button>
<span>0</span>
正如其他人所提到的,第一x++
不會有明顯的影響,因爲x
值加後更新了<span>
的內容。但那不是你原來的問題。
不,問題不是後增量。這是'document.write'。你能否明確提到這一點? – PeterMader
@PeterMader檢查更新的答案,然後! –