为什么这个函数执行多次?

问题描述 投票:0回答:1

我正在制作一个简单的预算程序,删除列表中的项目时,在刷新剩余预算时遇到了一些麻烦。函数budgetDeleteItem执行多次,但我不知道为什么。也许它与for循环中的beeing有关,但我不知道如何将其移出并仍使其工作。

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
<h1>Budget for the week</h1>
<form>

  <input id= "itemName" type="text" name="itemName" value="" placeholder="name of the item" >
  <input id = "itemCost" type="text" name="itemCost" value="" placeholder="cost of the item">

</form>
<button type="button" name="button"> Add new item </button>

   <ul>

   </ul>

  <p>total budget: <span id= "budget"> 100 </span> </p>

  </body>

  <script type="text/javascript">

const button= document.querySelector("button");
const ul= document.querySelector("ul");

button.addEventListener("click", checkEntry )

function checkEntry() {
  const itemName = document.getElementById("itemName").value;
  const itemCost = document.getElementById("itemCost").value;
  addItem(itemName, itemCost);
}

function addItem(itemName, itemCost){
  const li = document.createElement('li');
  li.innerHTML = ` <span class= "itemName">${itemName} </span>
    $ <span class=itemCost> ${itemCost} </span>
    <span class="delete"> X </span> `;
  ul.appendChild(li);
  deleteItem();
  budgetAddItem(itemCost);
}

function deleteItem(){
  const deleteButton = document.querySelectorAll(".delete");
  for (let i = 0; i < deleteButton.length; i++) {
    deleteButton[i].addEventListener("click", function(e) {
      if (e.target.classList.contains("delete")) {
        e.target.parentElement.remove();
        budgetDeleteItem(e);
      }
    })
 }
}
// Refreshes the remain budget whenever you add an Item
function budgetAddItem(itemCost){
const budgetContent = document.getElementById("budget").textContent;
const budgetContentParsed = parseInt(budgetContent);
const oldBudget = document.getElementById("budget");
const itemCostParsed = parseInt(itemCost);
const newBudget = budgetContentParsed - itemCostParsed;
oldBudget.innerHTML =`${newBudget}`;
}

// Refreshes the remain budget whenever you delete an Item
function budgetDeleteItem (e) {
const oldBudget = document.getElementById("budget");
const budgetContent = document.getElementById("budget").textContent;
const budgetContentParsed = parseInt(budgetContent);
const itemCost= e.target.parentElement.querySelector(".itemCost").textContent;
const itemCostParsed = parseInt(itemCost);
const newBudget = budgetContentParsed + itemCostParsed;
oldBudget.innerHTML =`${newBudget}`;
}




  </script>




</html>
javascript dom addeventlistener
1个回答
0
投票

如评论中所述,您正在创建重复的绑定。一种可行的方法是提供一种方法,以限制要向其添加新绑定的元素。考虑...

<span class="delete new"> X </span>

如果您使用两个类创建元素,那么您就有一个指示器来知道哪个是新的。然后...

const deleteButton = document.querySelectorAll(".delete.new");

由两个类选择仅获取新的。最后...

deleteButton[i].classList.remove('new');

要删除新类,以免将来再次选择它。

© www.soinside.com 2019 - 2024. All rights reserved.