簡體   English   中英

JavaScript項目總和

[英]Javascript sum of items

因此,使用Vanilla Javascript,我設法創建了一個下拉列表項目,一旦單擊按鈕,該項目就會添加到購物籃中。

我有一個“總成本”部分,該總成本部分應將添加到購物籃中的項目成本相加。 據我所知,我需要設置一個數組並分配一個價格。 但是,然后id需要將其與下拉列表(HTML)中的相應項目鏈接。 我認為我需要使用公式來總結這些。 最好的方法是什么? 還是有人可以給我舉個例子?

這是我所擁有的:

 var button = document.getElementById("button"); var select = document.getElementById("select"); var basket = document.getElementById("basket"); var totalCost = document.getElementById("total-cost"); function addToBasket() { var li = document.createElement("li"); li.innerHTML = select.options[select.selectedIndex].text; basket.appendChild(li); } document.getElementById("remove-button").onclick = function() { var list = document.getElementById("basket"); list.removeChild(list.childNodes[0]) } button.addEventListener("click", addToBasket); 
 <div id="select-items"> <form id="myForm"> <p>Item: <select id="select"> <option value="1" id="a">A</option> <option value="2" id="b">B</option> <option value="3" id="c">C</option> <option value="4" id="d">D</option> </select> <button id="button" type="button">Add</button></p> <button id="remove-button" type="button">Remove</button> </form> </div> <div id="basket-total"> <p>Basket</p> <div id="basket"></div> </div> <div id="total-of-basket"> <p>Total Cost</p> <p id="total-cost"></p> </div> 

我對此很陌生,因此非常感謝您的幫助! 謝謝!

這就是您想要用vanillaJS編寫的內容。 這不是很復雜,但也不是最簡單的。 它使用數組和一些您可能不熟悉的數組方法(foreach,reduce)。

基本概念是將項目封裝到具有namevalue屬性的Javascript對象中,然后將其添加到名為myBasket的數組中。 每次添加一項或刪除其中一項時,您都將重新計算總成本,並重新打印整個列表。 為簡單起見,我刪除了整個列表,然后從頭開始重新打印。

 var button = document.getElementById("button"); var select = document.getElementById("select"); var basket = document.getElementById("basket"); var totalCost = document.getElementById("total-cost"); var myBasket = []; function addToBasket() { var item = { value: Number(select.options[select.selectedIndex].value), name: select.options[select.selectedIndex].text }; myBasket.push(item) recalculate(); } function recalculate() { printBasket(); printCost(); } function printCost() { var cost = myBasket.reduce(function (acc, item) { return acc + item.value; }, 0); totalCost.innerText = cost; } function printBasket() { basket.innerHTML = ''; myBasket.forEach(function(item) { var li = document.createElement("li"); li.innerHTML = item.name; basket.appendChild(li); }) } document.getElementById("remove-button").onclick = function() { myBasket.pop(); recalculate(); } button.addEventListener("click", addToBasket); 
 <div id="select-items"> <form id="myForm"> <p>Item: <select id="select"> <option value="1" id="a">A</option> <option value="2" id="b">B</option> <option value="3" id="c">C</option> <option value="4" id="d">D</option> </select> <button id="button" type="button">Add</button></p> <button id="remove-button" type="button">Remove</button> </form> </div> <div id="basket-total"> <p>Basket</p> <div id="basket"></div> </div> <div id="total-of-basket"> <p>Total Cost</p> <p id="total-cost"></p> </div> 

這是您可以做什么的示例。 使此解決方案比您的設置更容易使用的原因是,只有一個陣列可以放置和移除選定的產品。 添加或刪除項目后,將調用refreshBasket方法,該方法將重新呈現購物籃內容和總價。

產品信息中有一個對象。 選項上的ID用於獲取匹配的產品信息。 此信息放置在所選項目的數組中。

我注意到,當購物籃為空時,您刪除項目的方法會產生錯誤。 您應先檢查是否有要刪除的項目,然后再刪除某些項目。

 const products = { a: { name: 'product A', price: 12.50 }, b: { name: 'product B', price: 7.25 }, c: { name: 'product C', price: 10 }, d: { name: 'product D', price: 17.90 } }, selectedItems = []; var button = document.getElementById("button"); var select = document.getElementById("select"); /** * Gets product information for the provided ID. Passing an ID that doesn't * have a matching product will return undefined. */ function getSelectedProduct(productId) { return products[productId]; } /** * Handles the event which is dispatched when the user adds an item to * the basket. */ function onAddItemToBasket(event) { // Get the option for the selected item. const selectedOption = select.options[select.selectedIndex], product = getSelectedProduct(selectedOption.id); // When there is no product with the ID, exit the method. if (product === undefined) { return; } // Add the selected item to the basket array with selected items. selectedItems.push(product); // Refresh the basket. refreshBasket(); } /** * Handles the event which is dispatched when the user removes an item from * the basket. */ function onRemoveItemFromBasket(event) { // When there are no items there is nothing to do. if (selectedItems.lenght === 0) { return; } // Remove the item at index 0 from the array. selectedItems.shift(); refreshBasket(); } function refreshBasket() { const basket = document.getElementById("basket"), totalCost = document.getElementById("total-cost"); // Create a string with item wrapped in an li element itemHTML = selectedItems.reduce((html, item) => html + `<li>${item.name} ($ ${item.price})</li>`,''), // Iterate over all the items and calculate the sum of all the items. totalPrice = selectedItems.reduce((total, item) => total + item.price, 0); // Update the inner HTML of the basket element with the items currently selected. basket.innerHTML = itemHTML; // Update the price of all the items combined. totalCost.innerHTML = `$ ${totalPrice}`; } const addTrigger = document.getElementById("button"), removeTrigger = document.getElementById("remove-button"); addTrigger.addEventListener('click', onAddItemToBasket); removeTrigger.addEventListener('click', onRemoveItemFromBasket) 
 <div id="select-items"> <form id="myForm"> <p>Item: <select id="select"> <option value="1" id="a">A</option> <option value="2" id="b">B</option> <option value="3" id="c">C</option> <option value="4" id="d">D</option> </select> <button id="button" type="button">Add</button></p> <button id="remove-button" type="button">Remove</button> </form> </div> <div id="basket-total"> <p>Basket</p> <div id="basket"></div> </div> <div id="total-of-basket"> <p>Total Cost</p> <p id="total-cost"></p> </div> 

一種技術是使用data-屬性將當前狀態存儲在DOM中。 這意味着將價格直接放在select元素上,並在select元素時查詢它們:

 var button = document.getElementById("button"); var select = document.getElementById("select"); var basket = document.getElementById("basket"); var totalCost = document.getElementById("total-cost"); function addToBasket() { var li = document.createElement("li"); li.innerHTML = select.options[select.selectedIndex].text; var price = Number(select.options[select.selectedIndex].dataset.price); li.dataset.price = price; basket.appendChild(li); totalCost.innerHTML = ((Number(totalCost.innerHTML) || 0) + price).toFixed(2); } document.getElementById("remove-button").onclick = function() { var list = document.getElementById("basket"); var price = Number(list.childNodes[0].dataset.price); list.removeChild(list.childNodes[0]); totalCost.innerHTML = ((Number(totalCost.innerHTML) || 0) - price).toFixed(2); } button.addEventListener("click", addToBasket); 
 div {float: left; margin-left: 3em;} 
 <div id="select-items"> <form id="myForm"> <p>Item: <select id="select"> <option value="1" data-price="1.23" id="a">A</option> <option value="2" data-price="2.35" id="b">B</option> <option value="3" data-price="7.11" id="c">C</option> <option value="4" data-price="9.87" id="d">D</option> </select> <button id="button" type="button">Add</button></p> <button id="remove-button" type="button">Remove</button> </form> </div> <div id="basket-total"> <p>Basket</p> <div id="basket"></div> </div> <div id="total-of-basket"> <p>Total Cost</p> <p id="total-cost"></p> </div> 

這與原來的問題相同,即在空籃子中“刪除”會引發錯誤。 那應該很容易解決,但是不在問題的范圍之內。

我實際上不認為這是您最好的選擇。 我認為將數據保留在JS變量中會更好。 但是,您需要一種方法,從產生下拉菜單的任何內容中獲取它們。 如果這是手動的,那不是問題,但是如果這是在服務器端生成的,則可能需要動態生成prices

 var button = document.getElementById("button"); var select = document.getElementById("select"); var basket = document.getElementById("basket"); var totalCost = document.getElementById("total-cost"); var prices = {a: 1.23, b: 2.35, c: 7.11, d: 9.87} // dynamically generated? var total = 0; function addToBasket() { var li = document.createElement("li"); total += prices[select.options[select.selectedIndex].id]; totalCost.innerHTML = total.toFixed(2); li.innerHTML = select.options[select.selectedIndex].text; li.itemId = select.options[select.selectedIndex].id; basket.appendChild(li); } document.getElementById("remove-button").onclick = function() { var list = document.getElementById("basket"); total -= prices[list.childNodes[0].itemId]; totalCost.innerHTML = total.toFixed(2); list.removeChild(list.childNodes[0]); } button.addEventListener("click", addToBasket); 
 div {float: left; margin-left: 3em;} 
 <div id="select-items"> <form id="myForm"> <p>Item: <select id="select"> <option value="1" data-price="1.23" id="a">A</option> <option value="2" data-price="2.35" id="b">B</option> <option value="3" data-price="7.11" id="c">C</option> <option value="4" data-price="9.87" id="d">D</option> </select> <button id="button" type="button">Add</button></p> <button id="remove-button" type="button">Remove</button> </form> </div> <div id="basket-total"> <p>Basket</p> <div id="basket"></div> </div> <div id="total-of-basket"> <p>Total Cost</p> <p id="total-cost"></p> </div> 

此解決方案仍然在DOM中存儲一些狀態-選擇項目的id屬性和新創建的購物籃項目的itemId 就是這樣。 計算使用這些ID在price對象中找到正確的prices ,然后使用javascript total變量存儲當前價格。

同樣,我不會在這里嘗試解決remove問題。


老實說,這仍然不是我真正喜歡的代碼。 我不喜歡全局變量,因此可能會找到一種將其嵌入其他范圍的方法。 我也將進行其他清理,但這可能會讓您步入正軌。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM