0

我正在关注 Dom javascript net ninja 系列,但我被卡住了,因为在我注入一个 'li' 元素后,删除功能不再起作用。我一开始也有类似的问题,querySelector() 方法不起作用,但是使用 setTimeout() 解决了,请您帮忙吗?

这是HTML代码:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <link href="style.css" rel="stylesheet" />
    <script src="cont.js"></script>
    <title>Testing JavaScript</title>
  </head>

  <body>
    <div class="wrapper">
      <header>
        <div id="page-banner">
          <h1 class="title">My Contacts</h1>
          <p>Special List</p>
          <form id="search">
            <input type="text" placeholder="Search Contacts..." />
          </form>
        </div>
      </header>

      <div id="Contact-List">
        <h2 class="title">Contacts</h2>
        <ul>
          <li>
            <span class="contat">Zineb Zrhari</span>
            <span class="delete">delete</span>
          </li>
          <li>
            <span class="contat">Kawter Lebouni</span>
            <span class="delete">delete</span>
          </li>
          <li>
            <span class="contat">Oumayma Touji</span>
            <span class="delete">delete</span>
          </li>
          <li>
            <span class="contat">Rim Essahel</span>
            <span class="delete">delete</span>
          </li>
        </ul>
      </div>
      <form id="add">
        <input type="text" placeholder="Add a Contact..." />
        <button>Add</button>
      </form>
    </div>
  </body>
</html>

和javascript代码:

window.setTimeout(() => {
  const list = document.querySelector("#Contact-List ul");

  // delete books
  list.addEventListener("click", function (e) {
    if (e.target.className == "delete") {
      const li = e.target.parentElement;
      li.parentNode.removeChild(li);
    }
  });

  // add book
  const addForm = document.forms["add"];
  addForm.addEventListener("submit", function (e) {
    e.preventDefault();
    const value = addForm.querySelector("input[type='text']").value;

    // create elements
    const li = document.createElement("li");
    const contact = document.createElement("span");
    const deleteBtn = document.createElement("span");

    // add contant
    deleteBtn.textContent = "delete";
    deleteBtn.classList.add("delete");
    contact.textContent = value;
    deleteBtn.classList.add("name");

    // append to document
    li.appendChild(contact);
    li.appendChild(deleteBtn);
    list.appendChild(li);
  });
});

谢谢!

4

1 回答 1

1

感谢您发布完整的代码。

问题在于这行 JavaScript:

if(e.target.className == 'delete'){

如果delete是唯一应用于元素的类,这将起作用。但是,您将两个类应用于新元素,这意味着e.target.className变为delete name.

您可以通过将行更改为:

if(e.target.classList.includes('delete')) {

即使元素有多个类,这也会起作用。

于 2020-06-28T17:45:56.210 回答