我正在尝试制作一个计分板,它奇怪地添加了数字:
我的html:
<div id="game-info">
Top score: <p id="top-score">0</p><br>
Current score: <p id="current">0</p><br>
Games played: <p id="played-games">0</p>
</div>
我的 JavaScript:
var score = document.getElementById("current");
if(blabla scored points){
score.innerHTML += 100;
}
if(blabla scored -points){
score.innerHTML -= 10;
}
负分工作得很好,至少它加起来是负数,但正分会自动添加到当前分数的末尾,如下所示:
Current score: <p id="current">0100</p><br>
或
Current score: <p id="current">-20100</p><br>
这与它是字符串而不是整数有什么关系吗?我很困惑为什么在相同的标记下负分起作用而正分不起作用..
最佳答案
连接字符串...您需要首先将当前分数转换为数字 - 尝试如下操作:
var score = document.getElementById("current");
if(blabla scored points){
// parse current score as integer and then add 100
score.innerHTML = parseInt(score.innerHTML,10) + 100;
}
if(blabla scored -points){
// parse current score as integer and then subtract 10
score.innerHTML = parseInt(score.innerHTML,10) - 10;
}
parseInt()
将字符串解析为整数
额外注意:使用parseInt()
并使用基数时
An integer that represents the radix of the above mentioned string. Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified.
关于javascript - html 文本中的分数字段在尝试 = -= 值时充当字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15657773/