最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to change innerHtml by adding a integer value to element? - Stack Overflow

programmeradmin3浏览0评论

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 ??

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 ??

Share Improve this question edited Jun 23, 2013 at 20:31 Sarthak Sharma asked Jun 23, 2013 at 20:24 Sarthak SharmaSarthak Sharma 7792 gold badges7 silver badges18 bronze badges 2
  • 1 String + int = String. :) – Achrome Commented Jun 23, 2013 at 20:26
  • 4 dom contents are strings. and are ALWAYS strings. you need to parse the string back to an int first. – Marc B Commented Jun 23, 2013 at 20:26
Add a ment  | 

1 Answer 1

Reset to default 10

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;
发布评论

评论列表(0)

  1. 暂无评论