点击按钮时如何更新ui

时间:2019-11-14 15:32:57

标签: javascript user-interface onclick mouseclick-event

每次尝试单击删除按钮之一时,我都尝试更新ui,但似乎不起作用。第一次单击第一条记录的删除按钮时,它可以正常工作。但是,当我单击另一个删除按钮以获取下一条记录时,它不起作用。 我的问题是,每次单击删除按钮后,我都不想刷新窗口。

请注意-我的添加功能可以正常工作

function list(type, text, cost, id) {
  var htmlContent = `<div>
                <div class='title'>${text}</div>
                <div class='type'>${type}</div>
                <div class='cost'>${cost}</div> 
                <div class='action' data-id='${id}'>
                        <button class='btn btn-danger delete'>
                        <i class="fas fa-trash-alt"></i></button>
                </div>          

        </div>`;
  var divWrapper = document.createElement("div");
  divWrapper.classList.add("listWrapper");
  divWrapper.innerHTML = htmlContent;

  return divWrapper;
} 


function display() {
  let incomeExpenses = storage.getItem("incomeExpenseList");

  JSON.parse(incomeExpenses).forEach(element => {
    const { type, text, cost, id } = element;

    listingDiv.appendChild(list(type, text, cost, id));
  });
}

function add(text, amount, type) {
  // copy initial array
  var copy = [...JSON.parse(storage.getItem("incomeExpenseList"))];
  //create item object
  var item = { id: `${copy.length + 1}`, text: text, cost: amount, type: type };
  copy.push(item);

  if (copy.length !== incomeExpenses) {
    incomeExpenses = copy;
    localStorage.setItem("incomeExpenseList", JSON.stringify(incomeExpenses));

    // refresh inner div and redipslay to the dom
    listingDiv.innerHTML = "";
    display(incomeExpenses);
  }
}




function deleteRecordRow(id) {
  var incomeExpenseList = JSON.parse(storage.getItem("incomeExpenseList"));
  // filter
  var newArr = incomeExpenseList.filter(function(element) {
    if (element.id !== id) {
      return element;
    }
  });
  // update local storage,
  localStorage.setItem("incomeExpenseList", JSON.stringify(newArr));
  // redisplay data to the window
  listingDiv.innerHTML = "";
  display(JSON.parse(storage.getItem("incomeExpenseList")));
} 



display(incomeExpenses);
var deleteBtns = document.querySelectorAll(".delete");

// loop thru over all detele btns

// function indexofItem(id, arr) {}

deleteBtns.forEach(function(element) {
  element.addEventListener("click", function() {
    // get id of the record from data id
    let recordId = this.parentNode.getAttribute("data-id");
    // delete from arr[a1,a2,...]
    deleteRecordRow(recordId);
  });
}); 

0 个答案:

没有答案