我是编程新手。每次我运行这段代码,什么都没有发生。你能告诉我这是为什么吗?
<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>
最佳答案
问题是你把 ++
和 --
放在变量之后,这意味着它将在打印后递增/递减变量它。尝试将其放在变量的之前,如下所示。
此外,如前所述,您在使用 document.write()
时遇到了一些问题。考虑来自 W3Schools page 的以下文档:
The
write()
method writes HTML expressions or JavaScript code to a document.The
write()
method is mostly used for testing. If it is used after an HTML document is fully loaded, it will delete all existing 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;
}
<input type=button value="increment" onclick="button1()" />
<input type=button value="decrement" onclick="button2()" />
<span id="output-area"></span>
关于javascript - 如何制作在单击时递增和递减值的按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45501207/