我不知道如何在JS中使用删除方法创建删除按钮/选项

I have no idea how to create a delete button / option using remove method in JS

提问人:VaQuellJQL 提问时间:9/18/2023 更新时间:9/18/2023 访问量:36

问:

我根本无法也不知道如何进行删除选项。我是编码的新手。我想在列表中已有的每个客人旁边有一个删除选项,以及将弹出的新客人。我知道我需要在客人项目符号列表的末尾添加一个关键字/变量,以便出现此按钮/选项,但我做不到。我希望它出现并工作,但我根本做不到,我一直在尝试许多方法,例如 removeChild 和 removeEvent Listener。

<!DOCTYPE html>
<html>

<body>
  <h2>Guest list</h2>
  <p id="demo"></p>
  <h3>Add a new guest!</h3>
  <form name="myform" action="">
    <span>Name:</span><input type="text" name="name" value="" />
    <span>Surname:</span><input type="text" name="surname" />
    <span>Age:</span><input type="text" name="age" />
    <input type="button" name="button" value="Add a guest" onClick="addAGuest(this.form)" />
  </form>
  <p style="color: red; font-weight: bold;" id="err"></p>
  <p onclick="removeButton()"style="color:darkorange; text-decoration: underline; cursor: pointer;" id="deleteButton">Delete this guest</p>
  <script>

 

    function getGuests() {
      const guests = [{ name: "James", surname: "Moth", age: 20 }, { name: "Ford", surname: "Mustang", age: "24" }, { name: "Jim", surname: "Smith", age: 19 },
      { name: "Christian", surname: "Neutron", age: 12 }];
      return guests;
    }

       function getBulletListOfGuests(guests) {
       let bulletList = "<ul>";
        for (i = 0; i < guests.length; i++) {
        bulletList = bulletList + "<li>The guest's name is " + guests[i].name + " " + guests[i].surname + " and they are " + guests[i].age + " years old." + "</li>"
       ;
      }
      return bulletList + "</ul>";
  }

  function removeButton(guests) {
      remove.guest;
    }

    const myGuests = getGuests();

    function resetErrorMessage() {
      document.getElementById("err").innerHTML = "";
    }

    function setErrorMessage(message) {
      document.getElementById("err").innerHTML = message;
    }

    function validateGuest(guest) {
      let errorMessage = "";
      if (guest.name == "") {
        errorMessage = errorMessage + "Name cannot be empty<br>";
      }
      if (guest.surname == "") {
        errorMessage = errorMessage + "Surname cannot be empty<br>"
      }
      if (guest.age == "") {
        errorMessage = errorMessage + "Age cannot be empty<br>";
      }
      return errorMessage;
    }

    function addAGuest(form) {
      const formData = new FormData(form);
      let guestToAdd = {};
      formData.forEach(function (value, key) {
        guestToAdd[key] = value;
      });
      let errorMessage = validateGuest(guestToAdd);
      resetErrorMessage();
      if (errorMessage == "") {
        myGuests.push(guestToAdd);
        displayListOfGuests(myGuests);
      } else {
        setErrorMessage(errorMessage);
      }
    }

    function displayListOfGuests(guests) {
      document.getElementById("demo").innerHTML = getBulletListOfGuests(guests);
    }

    displayListOfGuests(myGuests);
  </script>
</body>

</html>

我想在我添加的每位访客旁边显示一个删除按钮。我试过了

remove();

方法,但它似乎根本不起作用。如何设置一个变量,以便我可以将其放在来宾项目符号列表的末尾并实际使其工作?

JavaScript 按钮 方法

评论


答:

0赞 Ion Calancea 9/18/2023 #1

我建议使用 HTML DOM api 来处理行。

这段代码会变成......

let bulletList = "<ul>";
for (i = 0; i < guests.length; i++) {
        bulletList = bulletList + "<li>The guest's name is " + guests[i].name + " " + guests[i].surname + " and they are " + guests[i].age + " years old." + "</li>";
}

const list = document.createElement("ul");

for (i = 0; i < guests.length; i++) {
    const item = document.createElement("li");
    item.innerText = "<li>The guest's name is " + guests[i].name + " " + 
      guests[i].surname + " and they are " + guests[i].age + " years old." + "</li>";
    
   //create new button
   const removeButton = document.createElement("button");
   //add click event listener
   button.onclick = function() {
     //in this case "this" will be the button itself
     const row = this.closest('li');
     // removing entire row will make the work
     row.remove()
   }
// the text can be whatever you want
   button.innerText = "Delete Row"

    list.appendChild(item)
}
0赞 Bin Emmanuel 9/18/2023 #2

如果您的客人有 ID,这将使您的程序更容易确定要删除的客人,因此我对客人列表进行了修改。

请注意,您尝试执行的操作需要数据库/本地存储才能按预期工作。

const guests = [
    { id: 1, name: "James", surname: "Moth", age: 20 },
    { id: 2, name: "Ford", surname: "Mustang", age: "24" },
    { id: 3, name: "Jim", surname: "Smith", age: 19 },
    { id: 4, name: "Christian", surname: "Neutron", age: 12 },
];

我对 getBulletListOfGuest() 函数进行了小幅修改以添加删除按钮。删除按钮有一个名为 onclick 的属性,它采用我创建的名为 deleteGuest 的函数。

const guest = guests[i];

bulletList = bulletList +
    `<li>
         The guest's name is ${guest.name} ${guest.surname} and they are ${guest.age}years old.
         <button type="button" onclick="deleteGuest(${guest.id})">Delete</button>
    </li>`;

** deleteGuest** 函数获取用户正在尝试的来宾的 ID,然后可以将来宾从列表中筛选出来。

function deleteGuest(id) {
    const updateGuests = myGuests.filter(function (guest) {
        return guest.id !== id;
    });

    displayListOfGuests(updateGuests);
}