繁体   English   中英

我怎样才能像计算器一样总结我的选择?

[英]how can i sum my options like a calculator?

我正在制作一个菜单计算器,它可以为您提供所有产品,但我卡住了,因为我不知道从哪里开始, 我的计算器应用

我正在考虑使用 if else 语句并在每个按钮上放置多个 id 并以某种方式计算总数但我认为效率非常低所以如果有人有更好的主意,那将是完美的

.! 哦,顺便说一句! 我正在使用 create-element 和 appendchild 生成按钮元素。

这是我的代码

///////////////////HTML/////////////////////////

<body>
    <div class="icons-container" id="container">

    </div>
    <div class="displayer">
        <p>price</p>
        <p>total</p>
    </div>
</body>
</html>

/////////////////Javascript/////////////////////////

nombres = ['Kg','Taco','Dorado','1LtCSM','1/2CSM','Boing','Cafe','Refresco'];
precios = [440,30,24,50,25,20,20,25];

Total = [];


const element = document.querySelector('.icons-container');

for(i=0;i<=7;i++){
    let div = document.createElement('div');
    let h3 = document.createElement('h3');
    
    
    div.classList.add('cuadro');
    div.appendChild(h3);
    h3.textContent = `${nombres[i]}`;
    h3.classList.add('icon-text');
    element.appendChild(div);
    
};

我什么都没试过,但我想使用 if else 并在每个按钮上添加不同的 id 来区分每个按钮,

通过使用对象数组和.forEach()循环,我们以更简单的方式解决了您的所有问题。

在此处输入图像描述

使用此解决方案,无需向每个按钮添加class=""id="" ,因为我们使用了一个称为Closures的简单概念https://developer.mozilla.org/en-US/docs/Web/ JavaScript/Closures使.forEach()和 .addEventListener( .addEventListener()一起工作得很好!

 const menuData = [{ name: "Kg", price: 440, }, { name: "Taco", price: 30, }, { name: "Dorado", price: 24, }, { name: "1LtCSM", price: 50, }, { name: "1/2CSM", price: 25, }, { name: "Boing", price: 20, }, { name: "Cafe", price: 20, }, { name: "Refresco", price: 25, }, ]; generateGrid(menuData, document.querySelector(".icons-container")); function generateGrid(menuData, parent) { let total = 0; menuData.forEach((menuItem) => { const btn = document.createElement("button"); const h3 = document.createElement("h3"); btn.appendChild(h3); parent.appendChild(btn); h3.textContent = menuItem.name; const priceEl = document.getElementById("price"); const totalEl = document.getElementById("total"); btn.addEventListener("click", () => { total += menuItem.price; priceEl.textContent = menuItem.price; totalEl.textContent = total; }); }); }
 /* use your own css here, this is just for demo purposes */ body, .icons-container { gap: 0.5rem; }.icons-container, .displayer { display: grid; grid-auto-flow: column; grid-auto-columns: 1fr; }.displayer>div { text-align: center; }.displayer div>div { font-size: 200%; font-weight: bold; }
 <div class="icons-container"> <!-- JS will put the divs here --> </div> <div class="displayer"> <div> <p>price</p> <div id="price">0</div> </div> <div> <p>total</p> <div id="total">0</div> </div> </div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM