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>
答案 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)
您的代码中存在一些错误:
paidTotal
是一个元素,但是在paidTotal += personsCheck[i];
中您使用了一个数字变量。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>