作业:
1. ToList留言并添加删除功能
2. 使用JS动态一张表格,数据用数组进行模拟
1. ToList留言并添加删除功能
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ToList添加删除功能</title>
</head>
<body>
<h3>请留言</h3>
<input type="text">
<ul></ul>
<script>
var comment = document.querySelector('input');
var ul = document.getElementsByTagName('ul').item(0);
comment.focus();
comment.onkeydown = function (event) {
if (event.keyCode === 13) {
var li = document.createElement('li');
// 修改这条语句
// li.innerText = comment.value;
// innerText不能解析文本中的html代码,要换成innerHTML
// 将删除按钮添加到留言内容的后面
li.innerHTML = comment.value + '<a href="javascript:;" onclick="del(this)">删除</a>';
if (ul.childElementCount === 0) {
ul.appendChild(li);
} else {
// 如果列表已有留言,则插入到新一条之前
var first = ul.firstElementChild;
ul.insertBefore(li,first);
}
// 清空留言区,并设置焦点
comment.value = '';
comment.focus();
}
}
function del(ele) {
if (confirm('是否删除?')) {
var li = ele.parentNode;
li.parentNode.removeChild(li);
}
return false;
}
</script>
</body>
</html>点击 "运行实例" 按钮查看在线实例
2. 使用JS动态一张表格,数据用数组进行模拟
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js操作表格</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="cart2">
<caption>购物车2</caption>
<thead>
<tr>
<th>编号</th>
<th>品名</th>
<th>数量</th>
<th>单价</th>
</tr>
</thead>
<tbody></tbody>
</table>
<hr>
<script>
var data = [
{id: 1, name: '牛奶', count: 3, price: 50},
{id: 1, name: '苹果', count: 10, price: 80},
{id: 1, name: '衣服', count: 2, price: 600}
];
var cart2 = document.getElementById('cart2');
// 获取到tbody
var tbody = cart2.children[2];
data.forEach(function (value){
var tr = document.createElement('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>';
tbody.appendChild(tr);
})
</script>
</body>
</html>
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号