JavaScript 删除按钮到项目列表

huangapple go评论71阅读模式
英文:

JavaScript DELETE button to item list

问题

考虑以下代码:

function createDeleteButton(itemId) {
  const deleteButton = document.createElement("button");
  deleteButton.classList = "btn btn-danger";
  deleteButton.innerText = "删除";
  deleteButton.addEventListener("click", () => handleDeleteButtonClick(itemId)); // 添加点击事件监听器来处理删除按钮点击
  return deleteButton;
}

function handleDeleteButtonClick(itemId) {
  const row = event.target.closest("tr");
  row.remove();

  // 向远程API发送删除请求
  fetch(`${baseUrl}/items/${itemId}`, {
    method: "DELETE",
  })
    .then((response) => {
      if (!response.ok) {
        throw Error("删除项目时出错");
      }
      console.log("项目删除成功");
    })
    .catch((error) => {
      console.error(error);
    });
}

这段代码有点复杂。我如何简化它呢?或者我如何使用其他DOM代码来编写"closest"元素函数?

英文:

Consider:

function createDeleteButton(itemId) {
  const deleteButton = document.createElement("button");
  deleteButton.classList = "btn btn-danger";
  deleteButton.innerText = "Delete";
  deleteButton.addEventListener("click", ()=> handleDeleteButtonClick(itemId)); // Attach event listener to handle delete button click
  return deleteButton;
}



function handleDeleteButtonClick(itemId) {
  const row = event.target.closest("tr");
  row.remove();

  // Send delete request to the remote API
  fetch(`${baseUrl}/items/${itemId}`, {
    method: "DELETE",
  })
    .then((response) => {
      if (!response.ok) {
        throw Error("Error deleting item");
      }
      console.log("Item deleted successfully");
    })
    .catch((error) => {
      console.error(error);
    });
}

This code is so difficult. How can I shorten this?
Or how can I write the "closest" element function with other DOM code?

答案1

得分: 0

你需要将 event 传递给函数。

function createDeleteButton(itemId) {
  const deleteButton = document.createElement("button");
  deleteButton.classList = "btn btn-danger";
  deleteButton.innerText = "Delete";
  deleteButton.addEventListener("click", (e) => handleDeleteButtonClick(e, itemId)); // 将事件监听器附加到处理删除按钮点击的函数
  return deleteButton;
}

function handleDeleteButtonClick(event, itemId) {
  const row = event.target.closest("tr");
  row.remove();

  // 向远程API发送删除请求
  fetch(`${baseUrl}/items/${itemId}`, {
      method: "DELETE",
    })
    .then((response) => {
      if (!response.ok) {
        throw Error("Error deleting item");
      }
      console.log("Item deleted successfully");
    })
    .catch((error) => {
      console.error(error);
    });
}

请注意,代码部分未进行翻译。

英文:

You need to pass event to the function.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

function createDeleteButton(itemId) {
  const deleteButton = document.createElement(&quot;button&quot;);
  deleteButton.classList = &quot;btn btn-danger&quot;;
  deleteButton.innerText = &quot;Delete&quot;;
  deleteButton.addEventListener(&quot;click&quot;, (e) =&gt; handleDeleteButtonClick(e, itemId)); // Attach event listener to handle delete button click
  return deleteButton;
}

function handleDeleteButtonClick(event, itemId) {
  const row = event.target.closest(&quot;tr&quot;);
  row.remove();

  // Send delete request to the remote API
  fetch(`${baseUrl}/items/${itemId}`, {
      method: &quot;DELETE&quot;,
    })
    .then((response) =&gt; {
      if (!response.ok) {
        throw Error(&quot;Error deleting item&quot;);
      }
      console.log(&quot;Item deleted successfully&quot;);
    })
    .catch((error) =&gt; {
      console.error(error);
    });
}

<!-- end snippet -->

答案2

得分: 0

你不需要为每个按钮添加点击处理程序。实际上,你可以将它委托给 body,并检查点击了什么。

对于我的答案,我通过数据属性将项目添加到了按钮中,然后给按钮添加了一个额外的类 btn-delete

然后,我使用单个事件处理程序来检查点击的按钮,获取其ID,移除 tr 并将该ID传递给 fetch。

function createDeleteButton(itemId) {
  const deleteButton = document.createElement("button");
  deleteButton.classList = "btn btn-danger btn-delete";
  deleteButton.innerText = "Delete";
  deleteButton.dataset.id = itemId;
  return deleteButton;
}

document.body.addEventListener("click",(e) => {
  let el = e.target;
  if(el.classList.contains("btn-delete")){
      el.closest("tr").remove();

    fetch(`${baseUrl}/items/${el.dataset.id}`, {
      method: "DELETE",
    })
      .then((response) => {
        if (!response.ok) {
          throw Error("Error deleting item");
        }
        console.log("Item deleted successfully");
      })
      .catch((error) => {
        console.error(error);
      });
  }
});
英文:

You don't need add a click handler to each button. You can actually just delegate it to the body and check to see what was clicked on.

For my answer, I added the item it to the button via a data attribute, and then I gave the button an additional class of btn-delete.

Then I use a single event handler to check for the button clicked, get its ID, remove the tr and pass that ID to the fetch.

function createDeleteButton(itemId) {
  const deleteButton = document.createElement(&quot;button&quot;);
  deleteButton.classList = &quot;btn btn-danger btn-delete&quot;;
  deleteButton.innerText = &quot;Delete&quot;;
  deleteButton.dataset.id = itemId;
  return deleteButton;
}

document.body.addEventListener(&quot;click&quot;,(e) =&gt; {
  let el = e.target;
  if(el.classList.contains(&quot;btn-delete&quot;)){
      el.closest(&quot;tr&quot;).remove();

    fetch(`${baseUrl}/items/${el.dataset.id}`, {
      method: &quot;DELETE&quot;,
    })
      .then((response) =&gt; {
        if (!response.ok) {
          throw Error(&quot;Error deleting item&quot;);
        }
        console.log(&quot;Item deleted successfully&quot;);
      })
      .catch((error) =&gt; {
        console.error(error);
      });
  }
});

huangapple
  • 本文由 发表于 2023年6月8日 04:33:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76426936.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定