добавление прослушивателя событий внутри цикла переопределяет предыдущие данные

  function abc(){
    //model
class ShoppingCart{
    items;      //array 
    totalQty;   //number
    totalPrice; //number

    constructor(i,tq,tp)
        {
            this.items = i ;      
            this.totalQty = tq ;  
            this.totalPrice = tp; 
        }
}


class Product{
    title;
    price;
    qty;

    constructor(t,p,q){
        this.title=t;
        this.price=p;
        this.qty=q;
    }
}


function populate(){

    var sc = new ShoppingCart([],0,0);

    var p1 = new Product("earth",100,1);
    var p2 = new Product("water",200,3);
    var p3 = new Product("air",300,1);

    sc.items.push(p1);
    sc.items.push(p2);
    sc.items.push(p3);

    function computeTotalQuantity(){
        for(var i=0;i<sc.items.length;i++)
        {
            sc.totalQty += sc.items[i].qty
        }
    }

    function computeTotalPrice(){
        for(var i=0;i<sc.items.length;i++)
        {
            sc.totalPrice += sc.items[i].price
        }
    }

    function renderRows()
    {
        const cartTable = document.getElementById('cart-table');

        for(var i=0;i<sc.items.length;i++)   //row
        {
            var tableRow = document.createElement('tr'); 
            var rowId = sc.items[i]['title'];

            for(itemProperty in sc.items[i]){    //column
            var tableColumn = document.createElement('td');    
            tableColumn.innerHTML = sc.items[i][itemProperty]; 

              //earth //earth //earth
            var rowHeading = itemProperty;  //title //price //qty

            var columnId = rowId +'-' + rowHeading;
            tableRow.setAttribute('id',rowId);
            tableColumn.setAttribute('id',columnId);

            tableRow.appendChild(tableColumn);
           }


           var updateDropdown = document.createElement('select');
           updateDropdown.setAttribute('id',"update");

           for(var j=1;j<10;j++)
           {
               var option = document.createElement('option');
               option.setAttribute('value',j);
               option.innerHTML = j;


               if(j==sc.items[i]['qty']){
                   option.selected = true;
               }

               updateDropdown.appendChild(option);
           }



           var tableColumnDropdown = document.createElement('td');
           tableColumnDropdown.appendChild(updateDropdown);
           tableRow.appendChild(updateDropdown);


           //this is the portion where i am adding delete button
           var deleteId = rowId + '-' + 'delete';
           var tableColumnDelete = document.createElement('td');
           deleteButton = document.createElement('button');
           deleteButton.setAttribute('id',deleteId);



           deleteButton.innerText = "delete";
           console.log(rowId);
           //deleteButton.setAttribute('onclick','deleteEntireRow('+rowId+')');
           deleteButton.addEventListener('click',()=>{deleteEntireRow(rowId);},false);
           tableColumnDelete.appendChild(deleteButton);
           tableRow.appendChild(tableColumnDelete);

           cartTable.appendChild(tableRow);
        }
        cartTable.appendChild(tableRow);
    }

    function renderTotal(){
        var totalPrice = document.getElementById('total-price'); 
        var totalQty = document.getElementById('total-qty');

        totalPrice.innerHTML = sc.totalPrice;
        totalQty.innerHTML = sc.totalQty;

    }
    function init(){
        computeTotalPrice();
        computeTotalQuantity();
        renderRows();
        renderTotal();
    }


    //callback for all delete button
    function deleteEntireRow(id)
    {
        var toBeDeletedRow = document.getElementById(id);

        console.log(id);
        console.log(toBeDeletedRow);
        //toBeDeletedRow.remove();
    }

    init();
}

populate();
}

Я пытаюсь добавить кнопку удаления в свою таблицу для каждой строки и, следовательно, мне нужно добавить прослушиватель событий для события click, но мой прослушиватель событий переопределяет все старые данные. Я знаю, что этот вопрос задавали раньше, но все эти решения не работают для меня. Я попытался поместить весь код внутри функции и вызвать его там.


person ash1102    schedule 07.06.2020    source источник


Ответы (1)


Вам просто нужно bind уникально назначить каждую из кнопок, чтобы последняя не переопределяла все остальные.

  deleteButton.addEventListener('click',deleteEntireRow.bind(this, rowId));
person ABGR    schedule 07.06.2020