无法遍历输入并添加它们

时间:2018-10-25 05:44:57

标签: javascript

peoplePaid()在页面上通过添加按钮遍历页面上所有.persons类的输入时遇到问题。我认为这个问题是#paidTotal试图从.persons中的数组添加内容,但无法访问它们(在控制台中给我带来了未定义的错误)。

该变量有效,但前提是只有一个.persons类带有变量...

var personsCheck = parseFloat(document.getElementsByClassName('persons')[0].value);

但是,我需要它来动态循环通过.persons元素创建的数组的值。我想念什么?

function peoplePaid() {
  var checkTotal = parseFloat(document.getElementById('check').value);
  var personsCheck = document.getElementsByClassName('persons');
  var paidTotal = document.getElementById('paidTotal');

  for (var i = 1; i < personsCheck.length; i += 1) {
    paidTotal += personsCheck[i];
  }
  paidTotal.innerHTML = checkTotal - personsCheck;
}
$ <input type="text" id="check" value="" />

<h3>Number of People: <span id="numberOfPeople"></span></h3>

<div>
  <div id="userNumbers">
    <input type="text" class="persons" name="person">
  </div>
</div>

<button onclick="peoplePaid()">Calculate</button>
<!--Paid Amount-->
<div>
  <h3>Paid Amount: <span id="paidTotal"></span></h3>
</div>

2 个答案:

答案 0 :(得分:1)

paidTotal是一个元素。我相信您不想在元素本身上使用+=。您应该将总数添加到变量中。

此外,由于集合的索引基于0,因此必须从i开始0的值。您必须从每个元素中获取value属性。

请注意:在处理纯文本内容时,最好使用textContent而不是innerHTML

尝试以下方式:

function peoplePaid() {
  var checkTotal = parseFloat(document.getElementById('check').value);
  var personsCheck = document.getElementsByClassName('persons');
  var paidTotal = document.getElementById('paidTotal');
  var pCheck = 0;
  for (var i = 0; i < personsCheck.length; i += 1) {
    pCheck += personsCheck[i].value;
  }
  paidTotal.textContent = checkTotal - pCheck;
}
$ <input type="text" id="check" value="" />

<h3>Number of People: <span id="numberOfPeople"></span></h3>

<div>
  <div id="userNumbers">
    <input type="text" class="persons" name="person">
  </div>
</div>

<button onclick="peoplePaid()">Calculate</button>
<!--Paid Amount-->
<div>
  <h3>Paid Amount: <span id="paidTotal"></span></h3>
</div>

答案 1 :(得分:1)

您的代码中存在一些错误:

  1. paidTotal是一个元素,但是在paidTotal += personsCheck[i];中您使用了一个数字变量。
  2. 在循环中,索引必须从零开始而不是一个。
  3. 在这一行:paidTotal += personsCheck[i];中,您已经向personsCheck[i]添加了paidTotal元素而不是其值。

更正后的代码如下:

function peoplePaid() {
  var checkTotal = parseFloat(document.getElementById('check').value);
  var personsCheck = document.getElementsByClassName('persons');
  var paidTotal = 0;
  
  for (var i = 0; i < personsCheck.length; i += 1) {
    paidTotal += personsCheck[i].value * 1;
  }
  document.getElementById('paidTotal').innerHTML = checkTotal - paidTotal;
}
$ <input type="text" id="check" value="" />

<h3>Number of People: <span id="numberOfPeople"></span></h3>

<div>
  <div id="userNumbers">
    <input type="text" class="persons" name="person">
  </div>
</div>

<button onclick="peoplePaid()">Calculate</button>
<!--Paid Amount-->
<div>
  <h3>Paid Amount: <span id="paidTotal"></span></h3>
</div>