how to change innerHtml by adding a integer value to element?

牧云@^-^@ 提交于 2020-01-05 04:51:33

问题


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

   <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

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 230500 instead of 730. how to change my inner html value 230 in integer form ??


回答1:


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;


来源:https://stackoverflow.com/questions/17264978/how-to-change-innerhtml-by-adding-a-integer-value-to-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!