如何建立一個函數來將分配給按鈕的值相加?
P粉231112437
P粉231112437 2024-04-02 21:26:24
0
2
571

這裡是新編碼員。我正在創建一個披薩菜單應用程序,它將分配給頂部按鈕的值相加,並將它們顯示在列表底部的“總計”中。但我很難讓程式碼顯示添加配料時的成本。

以下是我嘗試過的:

let whiteWheat = document.getElementById("white-wheat");
let multiGrain = document.getElementById("multi-grain");
let caulifl = document.getElementById("cauliflower");
let thinCrust = document.getElementById("thin-crust");
let deepDish = document.getElementById("deep-dish");
let totalField = document.getElementById("total");
totalField = 0;

whiteWheat.addEventListener(click, function() {
  var totalCost = totalField + 10;
  var finalOrder = document.createElement("li");
  finalOrder.innerText = totalCost.value;
  totalField.appendChild(finalOrder);
});
<h1>PIZZA SUPREME</h1>
<h2>Select a crust and toppings to build your own pizza!</h2>
<h3>Crust</h3>
<h4> per crust.</h4>
<ul><button id="white-wheat">white wheat</button></ul>
<ul><button id="multi-grain">multigrain</button></ul>
<ul><button id="cauliflower">Cauliflower</button></ul>
<ul><button id="thin-crust">Thin Crust</button></ul>
<ul><button id="deep-dish">Deep Dish</button></ul>

<h2>Total:</h2>
<div id="total">
</div>

P粉231112437
P粉231112437

全部回覆(2)
P粉409742142

雷雷

P粉649990163

更好的方法可能是在按鈕上建立 x-price 屬性並將它們放入

中。這樣,您就可以使用單一事件偵聽器和事件傳播來新增 x-price 屬性的值。像這樣:

let totalPrice = 0;
const totalDiv = document.getElementById('total');
const itemsDiv = document.getElementById('items');

document.getElementById('buttons').addEventListener('click', e => {
  totalPrice += parseFloat(e.target.getAttribute('x-price'));
  totalDiv.textContent = totalPrice;
  
  const li = document.createElement('li');
  li.textContent = e.target.textContent;
  itemsDiv.appendChild(li);
});

PIZZA SUPREME

Select a crust and toppings to build your own pizza!

Crust

Total:

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板