【发布时间】:2017-06-07 08:20:56
【问题描述】:
我的 JS 正在根据用户输入的商品数量来更新商品总成本。但是我当前的“onclick”要求我传递一个索引位置来计算给定的行。
我希望能够一次更新所有行项目总计(基于用户的输入数量)。我可以在下面现有的 updatePriceByProduct 函数中执行此操作吗(可能使用 for 循环遍历所有行)?我什至不知道从哪里开始。
HTML
<div class="item-info-container">
<div class="page-header">
<h1>Iron <br> Merchandising Shop</h1>
</div>
<div class="item-row">
<div class="item-name"> <span> IronBubble-head </span> </div>
<div class="item-cost"> 25.00 </div>
<div class="item-quantity"> QTY
<input class="input-quantity">
</div>
<div class="item-total-price"> 0.00 </div>
<div class="item-delete"> <button class="delete-button">Delete</button> </div>
</div>
<div class="item-row">
<div class="item-name"> <span> IronShirt </span> </div>
<div class="item-cost"> 15.00 </div>
<div class="item-quantity">
<span> QTY
<input class="input-quantity" type="text">
</span>
</div>
<div class="item-total-price"> 0.00 </div>
<div class="item-delete"> <button class="delete- button">Delete</button> </div>
</div>
<div class="calculator">
<button class="calculate-button" onclick="updatePriceByProduct([0])"> Calculate Prices </button>
</div>
</div>
</div>
Javascript
function getPriceByProduct(index){
var stringPrice = document.getElementsByClassName("item-cost")[index].innerHTML; //Currently getting span id, not all elements
var numberPrice = Number(stringPrice);
return numberPrice;
}
function createQuantityInput(index){
var quantity = document.getElementsByClassName("input-quantity")[index].value; //retrieve quantity of item from form
return quantity;
}
function updatePriceByProduct(index){
var updatedPrice = getPriceByProduct(index) * createQuantityInput(index);
var itemTotal = document.getElementsByClassName("item-total-price")[index].textContent = updatedPrice;
return itemTotal;
}
【问题讨论】:
标签: javascript html for-loop foreach onclick