如何制作在单击时增加和减少值的按钮?

T. *_* Ou 3 html javascript jquery dom

我是编程新手。每次我运行这段代码时,什么都没有发生。你能告诉我这是为什么吗?

<body>
  <input type=button value="increment" onclick="button1()" />
  <input type=button value="decrement" onclick="button2()" />
  <script type="text/javascript">
    var x = 0
    document.write(x)

    function button1() {
      document.write(x++)
    }
    function button2(){
      document.write(x--)   
    }
  </script>
</body>
Run Code Online (Sandbox Code Playgroud)

Ang*_*ris 6

问题是,你把++-- 之后的变量,这意味着它会递增/递减打印后的变量。尝试将它放在变量之前,如下所示。

此外,如上所述,您在使用document.write(). 考虑来自W3Schools 页面的以下文档:

write()方法将 HTML 表达式或 JavaScript 代码写入文档。

write()方法主要用于测试。如果在 HTML 文档完全加载后使用它,它将删除所有现有的 HTML。

因此,document.write()只要您单击按钮,就会删除所有现有内容。如果要写入文档,请使用如下元素.innerHTML

var x = 0;

document.getElementById('output-area').innerHTML = x;

function button1() {
  document.getElementById('output-area').innerHTML = ++x;
}

function button2() {
  document.getElementById('output-area').innerHTML = --x;
}
Run Code Online (Sandbox Code Playgroud)
<input type=button value="increment" onclick="button1()" />
<input type=button value="decrement" onclick="button2()" />
<span id="output-area"></span>
Run Code Online (Sandbox Code Playgroud)


Pet*_*der 2

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--;
});
Run Code Online (Sandbox Code Playgroud)
<button id="increment">increment</button>
<button id="decrement">decrement</button>
<span>0</span>
Run Code Online (Sandbox Code Playgroud)

正如其他人提到的,第一个x++不会产生明显的效果,因为 的值在 的内容更新x会增加。但这不是你最初的问题。<span>