Home > Back-end >  How can I express these three button functions in a loop?
How can I express these three button functions in a loop?

Time:06-13

$("#addButton1").on("click", function(){
    let addMenu = new Menu(allMenu[0].Id, allMenu[0].Title);
    console.log(`newOrder : ${addMenu.mId}`);
    addToCart(addMenu);
});

$("#addButton2").on("click", function(){
    let addMenu = new Menu(allMenu[1].Id, allMenu[1].Title);
    console.log(`newOrder : ${addMenu.mId}`);
    addToCart(addMenu);
});
$("#addButton3").on("click", function(){
    let addMenu = new Menu(allMenu[2].Id, allMenu[2].Title);
    console.log(`newOrder : ${addMenu.mId}`);
    addToCart(addMenu);
});

CodePudding user response:

looks like

for(let i=0;i<allMenu.length;i  ){
   $(`#addButton${i 1}`).on("click", function(){
    let addMenu = new Menu(allMenu[i].Id, allMenu[i].Title);
    console.log(`newOrder : ${addMenu.mId}`);
    addToCart(addMenu);
});
}

CodePudding user response:

An excellent way to perform this action is by using class and data

HTML Code

<div>
    Product 1
    <span  data-product="1">Add to Cart</span>
</div>
<div>
    Product 1
    <span  data-product="2">Add to Cart</span>
</div>
<div>
    Product 3
    <span  data-product="3">Add to Cart</span>
</div>
<div>
    Product 4
    <span  data-product="4">Add to Cart</span>
</div>

add.js

$(".addToCart").on("click", function(){
    let product = $(this).data("product")
    let addMenu = new Menu(allMenu[product].Id, allMenu[product].Title);
    console.log(`newOrder : ${addMenu.mId}`);
    addToCart(addMenu);
});

CodePudding user response:

you can use prefix selector to selecting the similar elements,for example, selects those whose id starts with addButton,

addButton1,addButton2,addButtonme selects all of them because they all start with addButton

$('div[id^="addButton"]').

  • Related