批改状态:合格
老师批语:
本节知识点主要是学习表格的JS操作,涉及到的具体知识点有children子节点的寻找、table对象定义的一些属性(tHead、tBodies、tFoot、rows和cells)。
示例代码如下:
<!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>js操作表格的基本技巧</title>
<style>
table,
td,
th {
border: 1px solid #666;
}
table {
width: 500px;
border-collapse: collapse;
text-align: center;
}
table caption {
font-size: 1.2rem;
margin-bottom: 15px;
}
thead tr:nth-of-type(1) {
background-color: lightblue;
}
</style>
</head>
<body>
<table id="cart1">
<caption>购物车1</caption>
<!-- 注: 浏览器会自动给以下内容添加一个tbody容器 -->
<!-- 为防止作用js获取元素出错,我们手工添加上这个tbody -->
<!-- 将表头手工加上thead,否则会被添加二个tbody,因为table允许使用多个tbody -->
<thead>
<tr>
<th>编号</th>
<th>品名</th>
<th>数量</th>
<th>单价</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>手机</td>
<td>1</td>
<td>3000</td>
</tr>
<tr>
<td>2</td>
<td>电脑</td>
<td>1</td>
<td>5000</td>
</tr>
<tr>
<td>3</td>
<td>手机</td>
<td>1</td>
<td>3000</td>
</tr>
</tbody>
</table>
<hr>
<table id="cart2">
<caption>购物车2</caption>
<thead>
<tr>
<th>编号</th>
<th>品名</th>
<th>数量</th>
<th>单价</th>
</tr>
</thead>
<tbody></tbody>
</table>
<hr>
<script type="text/javascript">
// 获取电脑和单价
var cart1 = document.getElementById('cart1');
// 电脑在table的第3个子元素的第2个子元素下的第2个子元素的内容中
console.log(cart1.children[2].children[1].children[1].innerHTML);
// 单价able的第3个子元素的第2个子元素下的第4个子元素的内容中
console.log(cart1.children[2].children[1].children[3].innerHTML);
// 更新单元格的数据是, 使电脑价格变为 6000
cart1.children[2].children[1].children[3].innerHTML = 6000;
/*table对象定义一些属性,可以快速获取指定的子元素
1. tHead: <thead>
2. tBodies: <tbody>...复数
3. tFoot: <tfoot>
4. rows: 所有行
5. cells: 所有列*/
console.log(cart1.tBodies[0].rows[1].cells[3].innerHTML); //另一种更简单的写法
var data = [{
id: 1,
name: '牛奶',
count: 3,
price: 50
},
{
id: 2,
name: '苹果',
count: 10,
price: 80
},
{
id: 3,
name: '衣服',
count: 2,
price: 600
}
];
var cart2 = document.getElementById('cart2');
var tbody = cart2.children[2];
//遍历对象数组,value是一个对象
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);
// value.id
// value.name
// value.count
// value.price
})
</script>
</body>
</html>点击 "运行实例" 按钮查看在线实例
运行结果

手写代码

总结
1、
cart1.children[2].children[1].children[3].innerHTML和cart1.tBodies[0].rows[1].cells[3].innerHTML
含义相同,指代的都是在table的第3个子元素的第2个子元素下的第2个子元素的内容
2、
table对象定义一些属性,可以快速获取指定的子元素:(1). tHead: <thead> (2). tBodies: <tbody>...复数
(3). tFoot: <tfoot>(4). rows: 所有行(5). cells: 所有列
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号