我一直试图解决这个问题一段时间无济于事。当我只有一个价格时,页面上的按钮工作正常。所以,基本上你点击价格和数量,它就会增加小计,总数。但是,一旦我添加了第二个项目并将id更改为类,并且在submitButton = document.querySelectorAll(' .input-submit');我从querySelector更改为querySelectorAll,我收到此错误:未捕获TypeError:submitButton.addEventListener不是一个函数...不确定为什么...任何帮助将是欣赏它。
document.addEventListener('DOMContentLoaded', init);
var cart = {};
var ItemNode, quantityNode, costNode, submitButton, subtotalNode, totalNode, output;
function init(){
itemNode = document.querySelector('.input-item');
costNode = document.querySelector('.posterPrice');
quantityNode = document.querySelector('.qtyValue');
submitButton = document.querySelectorAll('.input-submit');
subtotalNode = document.getElementById('subtotal');
totalNode = document.querySelector('#total');
output = document.querySelector('.output');
submitButton.addEventListener('click', addPrice);
}
function addPrice(){
//addToCart(costNode.innerText, quantityNode.value);
//console.log(cart);
console.log('clicked');
}
// function addToCart(cost, quantity){
// //cart[item] = {};
// var itemObject = cart;
// itemObject["quantity"] = Number(quantity);
// itemObject["cost"] = Number(cost);
// //var itemTotal = cart["quantity"] * cart["cost"];
// console.log(itemTotal);
// for (var i = 0; i < itemTotal.length; i++){
// //subtotalNode.innerHTML = itemTotal++;
// //totalNode.innerHTML = itemTotal++;
// }
//console.log(itemTotal);
//}
&#13;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Gallery</title>
<link rel="stylesheet" href="style.css">
<script src="main.js"></script>
</head>
<body>
<h1 id='test'>Posters</h1>
<div class="posters">
<div id="poster1">
<div class="posterInfo">
<p>Price: $<span class="posterPrice">2.50</span></p>
<label for="qty" class="input-quantity">QTY:</label>
<input type="number" name="qty" class="qtyValue">
<button class="input-submit">Add to Cart</button>
</div>
</div>
<div id="poster2">
<div class="posterInfo">
<p>Price: $<span class="posterPrice">3.50</span></p>
<label for="qty" class="input-quantity">QTY:</label>
<input type="number" name="qty" class="qtyValue">
<button class="input-submit">Add to Cart</button>
</div>
</div>
</div>
<div id="poster3"></div>
<div id="poster4"></div>
<div id="poster5"></div>
</div>
<div class="total output">
<p>Subtotal: $<span id="subtotal"></span></p>
<p>Taxes: <span>$10.00</span></p>
<p>Shipping: <span>$10.00</span></p>
<p>Total: $<span id="total"></span></p>
</div>
<!--<script src="main.js"></script>-->
</body>
</html>
&#13;