批改状态:合格
老师批语:
一、ToList增删
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1>留言板ToList</h1>
<input type="text" name="comment" id="comment">
<ul></ul>
</body>
<script>
var comment = document.getElementById('comment');
var ul = document.getElementsByTagName('ul')[0];
comment.onkeydown = function (event){ //给文本框添加按键事件
if (event.keyCode === 13){
// 当键盘按下回车后执行
var li = document.createElement('li'); // 生成li标签
li.innerHTML = comment.value + '<a href="javascript:;" onclick="del(this)">删除</a>'; //将文本内容放入li中,并提供删除
ul.prepend(li); //将li放入ul中的最前面
comment.value = ''; //将文本框清空
}
}
// 执行留言区内容删除的函数
function del(ele){
if (confirm('确认要删除吗?')){
var li = ele.parentNode;
ul.removeChild(li);
}
return false;
}
</script>
</html>点击 "运行实例" 按钮查看在线实例
二、动态生成表格
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
table,
th,
td {
border: 1px solid #666;
}
table {
width: 500px;
text-align: center;
border-collapse: collapse;
}
table caption {
font-size: 1.2rem;
margin-bottom: 15px;
}
/* 这里必须在nth-of-type(1)前添加父元素,否则thead,tbody中的第一行都会生效 */
thead tr:nth-of-type(1) {
background-color: lightblue;
}
</style>
</head>
<body>
<table id="cart">
<caption>购物车</caption>
<thead>
<tr>
<th>编号</th>
<th>品名</th>
<th>数量</th>
<th>单价</th>
</tr>
</thead>
<tbody></tbody>
</table>
</body>
<script>
var data = [{
id: 1,
name: '牛奶',
count: 3,
price: 50
},
{
id: 2,
name: '苹果',
count: 10,
price: 80
},
{
id: 3,
name: '衣服',
count: 2,
price: 600
}
];
var cart = document.getElementById('cart');
var tbody = cart.children[2];
// 遍历数据
data.forEach(function (value) {
var tr = document.createElement('tr');
// 将每个td数据放入tr中
tr.innerHTML = '<td>' + value.id + '</td>';
tr.innerHTML += '<td>' + value.name + '</td>';
tr.innerHTML += '<td>' + value.count + '</td>';
tr.innerHTML += '<td>' + value.price + '</td>';
// 将tr追加到tbody
tbody.append(tr);
})
</script>
</html>点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号