Blogger Information
Blog 19
fans 0
comment 0
visits 10181
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
Dom元素增删改和留言板实战
搬砖来学php
Original
335 people have browsed it

Dom元素增删改

1.createElement(ele):创建新元素在,document 上调用

  1. // 一:增加
  2. // createElement(ele):创建新元素在,document 上调用。
  3. const ul = document.createElement("ul");
  4. // append,追加父级最后子节点后在父节点上使用
  5. document.body.append(ul);
  6. for (let i = 0; i < 5; i++) {
  7. const li = document.createElement("li");
  8. li.append("item-" + (i + 1));
  9. ul.append(li);
  10. }
  11. console.log(ul);

更改和删除

  1. // 二:更改
  2. // before:在某元素之前插入节点,在当前元素上调用
  3. // 1.创建一个新元素li
  4. const li = document.createElement("li");
  5. li.append("new item");
  6. li.style.color = "yellow";
  7. li.style.background = "blue";
  8. //获取第三个子元素
  9. const item = ul.querySelector("li:nth-of-type(3)");
  10. // const item = ul.querySelector('li:nth-of-type(3)');
  11. item.before(li);
  12. // 三;删除;remove(删除)
  13. // 删除最后一个ul
  14. ul.lastElementChild.remove();

留言板实战

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <title>留言板</title>
  8. </head>
  9. <body>
  10. <h1>留言板</h1>
  11. <input
  12. type="text"
  13. onkeydown="addMsg(this)"
  14. placeholder="清输入您对网站的评价"
  15. autofocus
  16. />
  17. <ul class="list"></ul>
  18. </body>
  19. <script>
  20. function addMsg(ele) {
  21. if (event.key === "Enter") {
  22. // 留言非空验证
  23. if (ele.value.length === 0) {
  24. alert("留言不能为空");
  25. ele.focus();
  26. return false;
  27. }
  28. // 2. 添加留言
  29. const ul = document.querySelector(".list");
  30. // 为每条留言添加删除功能
  31. ele.value =
  32. ele.value +
  33. '<button onclick="shanchu(this.parentNode)">删除</button>';
  34. ul.insertAdjacentHTML("afterbegin", `<li>${ele.value}</li>`);
  35. // 3. 清空输入框
  36. ele.value = null;
  37. }
  38. }
  39. // 删除功能
  40. function shanchu(ele) {
  41. return confirm("是否删除?") ? ele.remove() : false;
  42. }
  43. </script>
  44. </html>
Correcting teacher:PHPzPHPz

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post