批改状态:未批改
老师批语:
1、完成一个简单的用户留言本,熟悉基本的DOM元素的创建与添加与删除操作
<!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>完成一个简单的用户留言本</title>
</head>
<body>
<label for="comment">请留言:</label>
<!-- onkeydown(): 当用户按下键盘上某个键时触发该事件-->
<input type="text" id="comment" onkeydown="addComment(this)" autofocus>
<!-- 留言列表-->
<ul id="list"></ul>
<script>
function addComment(comment) {
if (event.keyCode === 13) {
if (comment.value === ''){
alert('请输入内容!');
return false;
} else {
// 1. 创建新留言,并添加到留言列表中
var item = document.createElement('li');
item.append(comment.value);
// 2. 将留言添加到列表中
var list = document.querySelector('#list');
if (list.childElementCount === 0) {
list.append(item);
} else {
var first = list.firstElementChild;
list.prepend(item,first);
}
// 3. 清空文本框
comment.value = '';
}
}
}
</script>
</body>
</html>点击 "运行实例" 按钮查看在线实例
2、创建一个对象数组,以它为表格数据, 将期填充到页面中的表格中,动态生成一张表
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>动态生成一张表</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="cart1">
<caption>成绩表</caption>
<thead>
<tr>
<th>姓名</th>
<th>语文</th>
<th>数学</th>
<th>英语</th>
</tr>
</thead>
<tbody></tbody>
</table>
<hr>
<table id="cart2">
<caption>成绩表</caption>
<thead>
<tr>
<th>姓名</th>
<th>语文</th>
<th>数学</th>
<th>英语</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script>
var data = [
{name: '张三', chin: 88, math: 30, english: 33},
{name: '李四', chin: 73, math: 66, english: 35},
{name: '王五', chin: 45, math: 96, english: 38}
];
var cart1 = document.getElementById('cart1');
// 获取到tbody
var tbody = cart1.children[2];
data.forEach(function (value){
var tr = document.createElement('tr');
tr.innerHTML = '<td>' + value.name + '</td>';
tr.innerHTML += '<td>' + value.chin + '</td>';
tr.innerHTML += '<td>' + value.math + '</td>';
tr.innerHTML += '<td>' + value.english + '</td>';
tbody.appendChild(tr);
});
// 用table属性完成
var cart2 = document.getElementById('cart2');
var tbody = cart2.tBodies[0];
for (var i = 0; i < data.length; i++) {
var tr = document.createElement('tr');
Object.keys(data[i]).forEach(function(key){
tr.innerHTML += '<td>' + data[i][key] + '</td>';
});
tbody.appendChild(tr);
}
</script>
</body>
</html>点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号