简体   繁体   English

在JavaScript中使用innerHTML更改值

[英]Changing value using innerHTML in Javascript

It's been a while since I've worked with Javascript and HTML coding. 自从我使用Javascript和HTML编码以来已经有一段时间了。 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. 我目前正在研究Home,当我淘汰了基础版后,基本上可以复制Away。

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. 当我选择“触地得分”链接时,它将添加6;当我选择“ PAT”链接时,它将6更改为7。但是当我再次选择“触地得分”时,它将在7之后添加6。

76
Touchdown PAT

How can I make the 7 change to a 13 when I select Touchdown again? 当我再次选择“触地得分”时,如何将7更改为13?

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. innerHTML是字符串,而不是整数。

To increment the current value, you could use parseInt : 要增加当前值,可以使用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). 编辑:正如Blender指出的那样,您还应该指定字符串是一个以10为底的数字( parseInt函数的第二个参数)。 Otherwise, numbers like 012 could be interpreted as an octal number. 否则,像012这样的数字可以解释为八进制数字。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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