JavaScript 基础
深入数据和类型
函数进阶
运算符
浏览器存储
Document
Web API
事件
工具与规范
实例
练习
$$demo <body> <button id="showBtn" onclick="showAdd()">显示添加框</button> <div id="box"></div> <table id="students"></table> </body> <script> let students = [ { name: "小明", score: 56 }, { name: "鸣人", score: 80 }, { name: "路飞", score: 70 }, ]
function fresh() {
let table = document.getElementById("students")
table.innerHTML = ""
for (let index in students) {
let student = students[index]
table.innerHTML += `<tr><td>${student.name}</td><td>${student.score}</td><td><button onclick="remove(${index})">删除</button></td></tr>`
}
}
function showAdd() {
let box = document.getElementById("box")
let showBtn = document.getElementById("showBtn")
if (box.innerHTML) {
showBtn.innerText = "显示添加框"
box.innerHTML = ""
} else {
showBtn.innerText = "隐藏添加框"
box.innerHTML =
'<input id="name" type="text" placeholder="学生姓名" />\
<input id="score" type="text" placeholder="分数" />\
<button onclick="add()">确定添加</button>'
}
}
function add() {
let name = document.getElementById("name")
let score = document.getElementById("score")
if (name.value && score.value) {
students.push({
name: name.value,
score: score.value,
})
name.value = ""
score.value = ""
fresh()
}
}
function remove(index) {
for (let i = index; i < students.length - 1; i++) {
students[i] = students[i + 1]
}
students.pop()
fresh()
}
fresh()
</script> <style> table { border-collapse: collapse; margin: 10px 0; }
table,
th,
td {
border: 1px solid;
}
td {
padding: 5px 10px;
}
</style>
$$