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检查更新的答案,然后! –