[英]Can i use textContent in JS for adding to element numbers?
I'm trying to make program that every time i click a button a numbers is being added to to a html element.我正在尝试编写程序,每次单击按钮时,都会将数字添加到 html 元素中。 I'm trying to do it using textContent like the code below, but every time the element "gets" the number, instead of doing the calculation and show the sum, its just adding the number as Like, instead doing that:
我正在尝试使用 textContent 来执行此操作,如下面的代码,但每次元素“获取”数字时,而不是进行计算并显示总和,它只是将数字添加为 Like,而不是这样做:
score: 2+4 >> score:6得分:2+4 >>得分:6
score: 6+1 >> score:7得分:6+1 >>得分:7
its doing that: score:241它这样做:得分:241
this is the code:这是代码:
HTML: HTML:
<div id="player1score">
<h2>score: <span id="sumscore1">0</span></h2>
<p id="player1dice">-</p>
</div>
JS: JS:
function render() {
let randomNumber = random()
sumscore1.textContent+= randomNumber
}
Maybe textContent cant gets numbers and attribute the numbers as string?也许 textContent 无法获取数字并将数字属性为字符串?
textContent
returns a string (or null
, in some cases). textContent
返回一个字符串(或null
,在某些情况下)。 Using the addition assignment operator +=
on a string results in a concatenation operation.对字符串使用加法赋值运算符
+=
会导致连接操作。
You need to cast it to an integer first to perform arithmetic operations on it:您需要先将其转换为 integer 才能对其执行算术运算:
function render() {
let randomNumber = random()
sumscore1.textContent = parseInt(sumscore1.textContent || 0) + randomNumber
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.