我有以下代码,但无法正常工作:
let item = document.querySelector('#item');
let price = document.querySelector('#price');
let input = document.querySelectorAll('.input');
let btn = document.querySelector('#btn');
let numb = [25, 15];
btn.addEventListener('click', function() {
Array.prototype.forEach.call(input, el => {
let i = +el.value;
let res = Array.prototype.reduce.call(input, (sum, e) => {
return sum + +e.value
}, 0);
if (el.value) {
item.textContent = res;
numb.forEach(elem => {
price.textContent = elem * i;
})
}
})
})
<p id="item">xxx</p>
<p id="price">xxx</p>
<input class="input" type="number">
<input class="input" type="number">
<button id="btn">Add</button>
我需要将每个输入的值与数组的第一个元素相关联,并乘以数组的第一个元素,然后将两个输入的总和相加。也就是说,第一个输入按顺序与数组的第一个元素关联。
答案 0 :(得分:0)
如果我正确理解了您想要的内容,则将输入顺序乘以您的numb数组,然后将它们相加,然后:
let item = document.querySelector('#item');
let price = document.querySelector('#price');
let total = document.querySelector('#total');
let input = document.querySelectorAll('.input');
let btn = document.querySelector('#btn');
let numb = [25, 15];
let elements = [item, price];
btn.addEventListener('click', function() {
let s = 0;
input.forEach((el, i) => {
const res = el.value*numb[i];
elements[i].textContent = res;
s += res;
});
total.textContent = s;
})
<p id="item">xxx</p>
<p id="price">xxx</p>
<input class="input" type="number">
<input class="input" type="number">
<button id="btn">Add</button>
<p id="total">xxx</p>