【问题标题】:How to make a function add value to a variable in JavaScript?如何让函数为 JavaScript 中的变量添加值?
【发布时间】:2023-01-14 01:04:38
【问题描述】:
我试图让一个按钮将一定数量的点添加到另一个变量,然后将变量的值显示为分数,但我似乎无法让它工作。
我尝试执行以下脚本,但每当我尝试对其进行测试时,整个分数变量都会消失,我不知道该怎么做
<button onclick="addPoints25()">done</button>
<p id="counter"></p>
<script>
var points = 0;
document.getElementById("counter").innerHTML = points;
function addPoints25() {
var points + 25;
}
</script>
【问题讨论】:
标签:
javascript
html
function
variables
【解决方案1】:
您只需要获取计数器的元素一次。
查看Addition_assignment了解如何连接/求和值的更多详细信息
let points = 0;
const counter = document.getElementById("counter");//get element
counter.textContent=points;//initial value of 0 set
function addPoints25() {
points += 25;//sum value
//console.log(points);//for debugging purposes
counter.textContent=points;//update value in element
}
<button onclick="addPoints25()">done</button>
<p id="counter"></p>
【解决方案2】:
调用函数时需要更新元素的textContent:
const counter = document.getElementById("counter");
let points = 0;
counter.textContent = points;
function addPoints25() {
points += 25;
counter.textContent = points;
}
<button onclick="addPoints25()">done</button>
<p id="counter"></p>
* 注意 use of const and let instead of var 和 textContent instead of innerHTML
【解决方案3】:
脚本中的问题是您试图重新分配变量“points”值,而不是将 25 添加到其当前值。如果您使用“+=”运算符将 25 添加到“点”的当前值,那将是最好的。此外,您应该在添加点后更新“counter”元素的 innerHTML,如下所示:
<button onclick="addPoints25()">done</button>
<p id="counter"></p>
<script>
var points = 0;
document.getElementById("counter").innerHTML = points;
function addPoints25() {
points += 25;
document.getElementById("counter").innerHTML = points;
}
</script>
这样,每次单击按钮时,“points”变量将增加 25,“counter”元素将更新为“points”变量的新值。