Pregunta

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

¿Fue útil?

Solución

change to

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

Otros consejos

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

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top