admin管理员组

文章数量:1355660

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

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

Share Improve this question asked Jan 24, 2013 at 4:15 Rock98Rock98 231 silver badge4 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

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/en-US/docs/JavaScript/Reference/Global_Objects/parseInt

You're gonna want to use parseInt on it so that Javascript knows you're talking about an integer and not just text.

本文标签: Changing value using innerHTML in JavascriptStack Overflow