javascript 如何通过向元素添加整数值来更改innerHtml?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17264978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to change innerHtml by adding a integer value to element?
提问by Sarthak Sharma
I build a Scoreboard
我建立一个记分牌
what it does when someone click the +500 button it will add 500 to the value in the score board i.e it will add 500 to the value of p tag
当有人点击 +500 按钮时它会做什么,它会将 500 添加到记分板中的值,即它将添加 500 到 p 标签的值
<div class="box">
<h2>Teams</h2>
<div class="score">
<p id="p1" class="lead">230</p>
</div>
/div>
<button id="b1">+500</button>
JavaScript for it
JavaScript
var myScore = document.getElementById("b1");
myScore.onclick = function () {
var newScore = document.getElementById("p1").innerHTML;
var value = newScore + 500;
document.getElementById("p1").innerHTML = value;
};
but this is showing me 230500instead of 730. how to change my inner html value 230 in integer form ??
但这向我展示了 230500而不是730。如何以整数形式更改我的内部 html 值 230 ?
回答by Denys Séguret
Right now, you're adding an integer to a string, so you're making a string concatenation.
现在,您正在向字符串添加一个整数,因此您正在进行字符串连接。
Change
改变
var value = newScore + 500;
to
到
var value = parseInt(newScore,10) + 500;