博主信息
博文 45
粉丝 0
评论 1
访问量 40668
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
创建对象数组,以表格数据填充到页面表格中,动态生成一张表
源逸
原创
1890人浏览过

1.获取到页面中的表格的元素id值和当前表格的tbody(tBodies是复数)

2.使用for遍历对象数组获取到下标,再使用forEach遍历获取到对象数组中的值,动态生成行,把数据插入到行内

QQ图片20190519215821.png

实例

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>动态生成表格数据(创建对象数组,使用循环遍历动态生成渲染到页面)2019.05.09</title>
	<style>
		table,th,td{
			border:1px solid #666;
		}
		table{
			margin:0 auto;
			width:500px;
			text-align:center;
			border-collapse: collapse;
		}
		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>
		
		<thead>
			<tr>
				<th>编号</th>
				<th>品名</th>
				<th>数量</th>
				<th>单价</th>
			</tr>
		</thead>
		<tbody>
			<tr>
				<td>1</td>
				<td>手机</td>
				<td>1</td>
				<td>5000</td>
			</tr>
			<tr>
				<td>1</td>
				<td>水果</td>
				<td>6</td>
				<td>800</td>
			</tr>
			<tr>
				<td>1</td>
				<td>笔记本</td>
				<td>9</td>
				<td>6000</td>
			</tr>
			<tr>
				<td>1</td>
				<td>手提</td>
				<td>1</td>
				<td>500</td>
			</tr>			
		</tbody>
	</table>
	<table id="cart2">
		<caption>购物车1</caption>
		
		<thead>
			<tr>
				<th>编号</th>
				<th>品名</th>
				<th>数量</th>
				<th>单价</th>
			</tr>
		</thead>
		<tbody></tbody>
		</table>

	<table id="cart3">
		<caption>购物车1</caption>	
		<thead>
			<tr>
				<th>编号</th>
				<th>品名</th>
				<th>数量</th>
				<th>单价</th>
			</tr>
		</thead>
		<tbody></tbody>
		</table>

		<script>
		//创建对象数组
		var data = [
			{id: 1, name: '牛奶', count: 3, price: 50},
            {id: 1, name: '苹果', count: 10, price: 80},
            {id: 1, name: '衣服', count: 2, price: 600}
		];

		//获取表格2
		var tbody = document.getElementById('cart2');

		//遍历对象数组
		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);
		});

		var cart3 = document.getElementById('cart3');
		var tbody = cart3.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>

运行实例 »

点击 "运行实例" 按钮查看在线实例


批改状态:未批改

老师批语:
本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系admin@php.cn举报处理!
全部评论 文明上网理性发言,请遵守新闻评论服务协议
0条评论
作者最新博文
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号

  • 登录PHP中文网,和优秀的人一起学习!
    全站2000+教程免费学