简体   繁体   中英

Changing value using innerHTML in Javascript

It's been a while since I've worked with Javascript and HTML coding. I am trying to construct a basic scoreboard system that will add points to the home and away scores as the points are earned. I am currently working on the Home right now and will basically replicate the Away when I've knocked out the basic.

Here's my code:

<script type="text/javascript">

function addTD(){

    document.getElementById("score").innerHTML +=6;

}

function addPAT(){document.getElementById("score").innerHTML ++;}

</script>

<div id="score"></div>

<a href="javascript:addTD();">Touchdown</a>
<a href="javascript:addPAT();">PAT</a>

When I select the Touchdown link, it adds a 6 and when I select the PAT link, it changes the 6 to a 7. But when I go to select Touchdown again, it adds the 6 after the 7.

76
Touchdown PAT

How can I make the 7 change to a 13 when I select Touchdown again?

Thanks in advance for your help. Brandon

change to

function addTD(){            
   document.getElementById("score").innerHTML=
        parseInt(document.getElementById("score").innerHTML,10)+6;
}

innerHTML is a string, not an integer.

To increment the current value, you could use parseInt :

function addPAT(){
    var scoreEl = document.getElementById("score");
    scoreEl.innerHTML = parseInt(scoreEl.innerHTML, 10) + 1;
}

Edit: As Blender noted, you should also specify that the string is a base-10 number (second argument of the parseInt function). Otherwise, numbers like 012 could be interpreted as an octal number.

MDN Link: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt

您将要在其上使用parseInt ,以便Javascript知道您在谈论整数,而不仅仅是文本。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM