JavaScript 综合练习 3
1. 案例演示
2. 代码实现
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><meta http-equiv="X-UA-Compatible" content="IE=edge" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>js综合案例3</title></head><body><input type="text" id="input" /><ul id="list"></ul><script>const array = [{name: "张三",id: 1001,},{name: "李四",id: 1002,},{name: "王五",id: 1003,},{name: "狗蛋",id: 1004,},];const list = document.getElementById("list");const input = document.getElementById("input");const removeAllChild = () => {const lis = document.querySelectorAll("li");if (lis.length) {for (let i = 0; i < lis.length; i++) {list.removeChild(lis[i]);}}};const renderList = (array) => {removeAllChild();for (let i = 0; i < array.length; i++) {const item = array[i];console.log(item);const li = document.createElement("li");li.innerHTML = item.name;list.appendChild(li);}};renderList(array);input.onkeydown = (e) => {if (e.keyCode === 13) {const value = Number(e.target.value);const targetIndex = array.findIndex((item) => {return item.id === value;});if (targetIndex >= 0) {array.splice(targetIndex, 1);renderList(array);}}};</script></body>
</html>