简体   繁体   English

我可以在 JS 中使用 textContent 来添加元素编号吗?

[英]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.

相关问题 JS中创建的元素上的textContent不起作用? - textContent on created element in JS not working? 我可以在 JS `e` 数字中使用变量吗? - Can I use variables in JS `e` numbers? 是否可以将元素的textContent分配为JS中的HTML代码? - is it possible to assign the textContent of an element to be HTML code in JS? 如何将换行符/回车符插入到 element.textContent 中? - How can I insert new line/carriage returns into an element.textContent? 我可以将值的“目标”(即SpanID.textContent)存储在数组中吗? (HTML / JS) - Can I store the “destination” (i.e. SpanID.textContent) of a value in an array? (HTML/JS) 我可以访问元素(输入标签),但不能访问 textContent 和 innerText 的内容 - i can access the element(input tag) but not its content for neither textContent nor innerText 是否可以更改作为文本元素克隆的svg use元素的textContent值? - Is it possible to change the textContent value of an svg use element that is a clone of a text element? 无法设置自定义内置元素的 textContent 除非超时 - Can't set textContent of a customised built-in element except in timeout 如何使用数组和 JS 替换 html 元素中的类? - How can I use arrays and JS to replace classes in a html element? 如何使用JS函数更改页面中的元素样式 - how can I use a JS function to change an element style in the page
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM