添加输入不会改变javascript

时间:2014-10-03 01:06:38

标签: javascript html

我正在尝试添加3个类型为数字的输入元素。由于某种原因,这不起作用。当我取出if语句时,它可以工作,但只有在我改变了第一个(score1)之后。当我改变其他人时,没有任何反应。感谢。

function getTotal() {

var score1 = document.getElementById("score1");
var score2 = document.getElementById("score2");
var score3 = document.getElementById("score3");

var sc1 = parseInt(score1.value);
var sc2 = parseInt(score2.value);
var sc3 = parseInt(score3.value);

if (isNan(sc1)) {
    sc1 = 0;
}

if (isNan(sc2)) {
    sc2 = 0;
}

if (isNan(sc3)) {
    sc3 = 0;
}

var total = sc1 + sc2 + sc3;
document.getElementById("totalScore").innerHTML = total;

}

function assign() {
    var score1 = document.getElementbyId("score1");
    var score2 = document.getElementbyId("score2");
    var score3 = document.getElementbyId("score3");    

    score1.onchange = getTotal;
    score2.onchange = getTotal;
    score3.onchange = getTotal;
}


<!DOCTYPE html>
<html>
  <head>
    <script src="getTotal.js"  type="text/javascript"></script>
  </head>
  <body>
    <header>
      <tbody>
        <tr>
          <td>
            Total: 
            <output id="total" class="totalScore"></output>
          </td>
        </tr>
      </tbody>
    </header>
  <table>
    <tbody>
      <td>Score 1</td>
      <td><input type="number" id="score1"/></td>

      <td>Score 2</td>
      <td><input type="number" id="score2" /></td>

      <td>Score 3</td>
      <td><input type="number" id="score3" /></td>
    </tbody>
  </table>

   <script type="text/javascript">assign();</script>

  </body>
 </html>

2 个答案:

答案 0 :(得分:2)

拼写错误。

var score1 = document.getElementbyId("score1");
var score2 = document.getElementbyId("score2");
var score3 = document.getElementbyId("score3");  

如果您检查控制台,则会在您调用score1的行上看到错误Uncaught TypeError: undefined is not a function。选择器为document.getElement*By*Id,您正在编写by小写..

答案 1 :(得分:0)

您的<output>有一个id属性,其值为&#34;总计&#34;而你的班级属性&#39;价值是&#34;总计&#34;。考虑将id值更改为&#34; totalscore&#34;或者将getElementById的值更改为&#34;得分&#34;