admin管理员组

文章数量:1401307

I made a "shopping" website but each Quantity selector needs its own lines of code, creating a lot of duplicates. How can I use the same code for each quantity selector?

Image of the site

some filler since stack overflow wont let me post my question bc its mostly code even though my question is how to use less code

<tr>
                <td>
                    <span id="price_log">2.23</span>
                    <img src="ShopStuff/gold_coin.png" style="width:20px; height:20px;">
                </td>
                <td>
                    <span id="price_leaf">0.28</span>
                    <img src="ShopStuff/gold_coin.png" style="width:20px; height:20px;">
                </td>
                <td>
                    <span id="price_stone">0.14</span>
                    <img src="ShopStuff/gold_coin.png" style="width:20px; height:20px;">
                </td>
                <td>
                    <span id="price_melon">2.80</span>
                    <img src="ShopStuff/gold_coin.png" style="width:20px; height:20px;">
                </td>
            </tr>
            <tr>
                <td>
                    <input type="button" value="-" onclick="updateQuantity('log', -1)">
                    <input type="number" id="log" value="0" min="0" onchange="updateQuantity('log', 0)">
                    <input type="button" value="+" onclick="updateQuantity('log', 1)">
                    <br>
                    Total: <span id="total_log">0.00</span>
                    <img src="ShopStuff/gold_coin.png" style="width:20px; height:20px;">
                </td>
                <td>
                    <input type="button" value="-" onclick="updateQuantity('leaf', -1)">
                    <input type="number" id="leaf" value="0" min="0" onchange="updateQuantity('leaf', 0)">
                    <input type="button" value="+" onclick="updateQuantity('leaf', 1)">
                    <br>
                    Total: <span id="total_leaf">0.00</span>
                    <img src="ShopStuff/gold_coin.png" style="width:20px; height:20px;">
                </td>
                <td>
                    <input type="button" value="-" onclick="updateQuantity('stone', -1)">
                    <input type="number" id="stone" value="0" min="0" onchange="updateQuantity('stone', 0)">
                    <input type="button" value="+" onclick="updateQuantity('stone', 1)">
                    <br>
                    Total: <span id="total_stone">0.00</span>
                    <img src="ShopStuff/gold_coin.png" style="width:20px; height:20px;">
                </td>
                <td>
                    <input type="button" value="-" onclick="updateQuantity('melon', -1)">
                    <input type="number" id="melon" value="0" min="0" onchange="updateQuantity('melon', 0)">
                    <input type="button" value="+" onclick="updateQuantity('melon', 1)">
                    <br>
                    Total: <span id="total_melon">0.00</span>
                    <img src="ShopStuff/gold_coin.png" style="width:20px; height:20px;">
                </td>
            </tr>

I made a "shopping" website but each Quantity selector needs its own lines of code, creating a lot of duplicates. How can I use the same code for each quantity selector?

Image of the site

some filler since stack overflow wont let me post my question bc its mostly code even though my question is how to use less code

<tr>
                <td>
                    <span id="price_log">2.23</span>
                    <img src="ShopStuff/gold_coin.png" style="width:20px; height:20px;">
                </td>
                <td>
                    <span id="price_leaf">0.28</span>
                    <img src="ShopStuff/gold_coin.png" style="width:20px; height:20px;">
                </td>
                <td>
                    <span id="price_stone">0.14</span>
                    <img src="ShopStuff/gold_coin.png" style="width:20px; height:20px;">
                </td>
                <td>
                    <span id="price_melon">2.80</span>
                    <img src="ShopStuff/gold_coin.png" style="width:20px; height:20px;">
                </td>
            </tr>
            <tr>
                <td>
                    <input type="button" value="-" onclick="updateQuantity('log', -1)">
                    <input type="number" id="log" value="0" min="0" onchange="updateQuantity('log', 0)">
                    <input type="button" value="+" onclick="updateQuantity('log', 1)">
                    <br>
                    Total: <span id="total_log">0.00</span>
                    <img src="ShopStuff/gold_coin.png" style="width:20px; height:20px;">
                </td>
                <td>
                    <input type="button" value="-" onclick="updateQuantity('leaf', -1)">
                    <input type="number" id="leaf" value="0" min="0" onchange="updateQuantity('leaf', 0)">
                    <input type="button" value="+" onclick="updateQuantity('leaf', 1)">
                    <br>
                    Total: <span id="total_leaf">0.00</span>
                    <img src="ShopStuff/gold_coin.png" style="width:20px; height:20px;">
                </td>
                <td>
                    <input type="button" value="-" onclick="updateQuantity('stone', -1)">
                    <input type="number" id="stone" value="0" min="0" onchange="updateQuantity('stone', 0)">
                    <input type="button" value="+" onclick="updateQuantity('stone', 1)">
                    <br>
                    Total: <span id="total_stone">0.00</span>
                    <img src="ShopStuff/gold_coin.png" style="width:20px; height:20px;">
                </td>
                <td>
                    <input type="button" value="-" onclick="updateQuantity('melon', -1)">
                    <input type="number" id="melon" value="0" min="0" onchange="updateQuantity('melon', 0)">
                    <input type="button" value="+" onclick="updateQuantity('melon', 1)">
                    <br>
                    Total: <span id="total_melon">0.00</span>
                    <img src="ShopStuff/gold_coin.png" style="width:20px; height:20px;">
                </td>
            </tr>
Share Improve this question asked Mar 23 at 4:26 SpleefiesSpleefies 1 2
  • Add your event handler to a parent object (perhaps your <table>), then use event delegation to handle events from anywhere in the table. Use this or the target property of the event object to work out what to do. – Tangentially Perpendicular Commented Mar 23 at 4:38
  • If you're looking for an answer that comprises of only HTML (as your tag and question infers), that's impossible. You need JavaScript, post updateQuantity() and add a JavaScript tag. – zer00ne Commented Mar 24 at 10:37
Add a comment  | 

2 Answers 2

Reset to default 0

You could make the buttons programmatically like this:

// Target the items
const shopItems = document.querySelectorAll('td')

// Add buttons to items
shopItems.forEach(item => {

  // Get item name through ID
  const itemName = item.querySelector('input').id

  // Create buttons
  const decreaseQuantityButton = document.createElement('button')
  decreaseQuantityButton.setAttribute('onClick', `javascript: updateQuantity(${itemName}, -1)`)
  const increaseQuantityButton = document.createElement('button')
  increaseQuantityButton.setAttribute('onClick', `javascript: updateQuantity(${itemName}, 1)`)

  // Append children
  item.appendChild(decreaseQuanitityButton)
  item.appendChild(increaseQuanitityButton)
})

You can change the order of the buttons and where they are in the item container to however you want but this is the basic idea; create elements in js that will be added and function no matter how many items you have.

As your example code was not complete I took the liberty of adding the bit with the product pictures and names. I also changed the layout a little in order to make it responsive. I replaced your table-TDs with divs in inline-block mode. This will place as may divs in one row as fitting on the current screen. This is just a "quick and dirty" fix to illustrate the principle.

With regards to your HTML generation and the upd8() function behind it doing the calculations I relied on the template string syntax of JavaScript and event delegation. The event listeners are added onto the div.body only once and are thereby effective for the targeted tags inside it (as required for each event type etype).

All product specific data is contained in the array of arrays products which can easily be extended now.

const coin="https://png.pngtree/png-clipart/20220119/ourmid/pngtree-game-coin-gold-coin-design-png-image_4234274.png",
  picsum="https://picsum.photos/id/",
  products=[
   ["log",2.23,"160"],["leaf",.28,"21"],["stone",.14,"1"],
   ["melon",2.8,"175"],["apple",1.35,"30"],["orange",1.78,"39"],
   ["banana",.85,"48"]],
  bdy=document.querySelector(".body"),
   ttl=document.getElementById("total");

bdy.innerHTML=products.map(([name,price,pic])=>
`<div class="td"><img src="${picsum+pic}/200" class="prod"><br>${name}<br><span class="price">${price}</span>
 <img class="coin" src="${coin}"><br>
 <button type="button">-1</button><input
 type="number" name="${name}" value="0" min="0"><button
 type="button">+1</button><br>
 Total: <span class="total">0.00</span>
 <img class="coin" src="${coin}"></div>`).join("");

[["click","BUTTON"],["input","INPUT"]].forEach(([etype,tag])=>
 bdy.addEventListener(etype,upd8(tag))
);
function upd8(tag){
 return function(ev){
  if(ev.target.tagName==tag){
   const div=ev.target.closest(".td"),
amount=div.querySelector("input"),
price=div.querySelector(".price"),
total=div.querySelector(".total");
   amount.value= Math.max(+amount.value + +(ev.target.textContent??0),0);
   total.textContent=(amount.value * price.textContent).toFixed(2);
   ttl.textContent=[...bdy.querySelectorAll(".total")].reduce((a,c)=>+c.textContent+a,0).toFixed(2);  
}}}
.td {display: inline-block;
 text-align: center;
 border: 1px solid gray;
 padding: 4px; margin:4px} 
.coin {width:20px;height:20px}
.td input {width:80px}
<div class="body"></div>
Total order: <span id="total">0.00</span> <img class="coin" src="https://png.pngtree/png-clipart/20220119/ourmid/pngtree-game-coin-gold-coin-design-png-image_4234274.png">

本文标签: htmlHow can I remove duplicatesStack Overflow