运用jQuery动态向html中添加表格元素
程序员文章站
2022-05-30 10:13:07
...
实现的功能是运用jQuery动态的向一个table中添加行元素,很简单,也不废话,直接上代码。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>点赞统计</title>
</head>
<style type="text/css">
.tdClass{
width: 26vw;
border: 1px solid #cccccc
}
</style>
<body>
<div style="color: #FF6600;font-size: 6.5vw;width: 100%;text-align: center;margin-top: 8vw">快乐大本营</div>
<div style="font-size: 4.2666vw;text-align: center;margin: 7vw 0">分组点赞排名</div>
<table id = "group" style="width: 80vw;display: flex;margin: auto;font-size: 3.5vw;text-align: center;border-collapse:collapse;">
<tr>
<td class="tdClass">排名</td>
<td class="tdClass">组名</td>
<td class="tdClass">票数</td>
</tr>
</table>
<div style="font-size: 4.2666vw;text-align: center;margin: 7vw 0">个人点赞排名</div>
<table id = "alone" style="margin-bottom: ;width: 80vw;display: flex;margin: auto;font-size: 3.5vw;
text-align: center;border-collapse:collapse;margin-bottom: 7vw">
<tr>
<td class="tdClass">排名</td>
<td class="tdClass">姓名</td>
<td class="tdClass">票数</td>
</tr>
</table>
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="js/request.js"></script>
</body>
</html>
在没添加元素之前,显示入下图所示:
var group = [{name:"1班",num:100},
{name:"2班",num:150},
{name:"3班",num:200},
{name:"4班",num:250},
{name:"5班",num:300},
{name:"6班",num:350},
{name:"7班",num:400}]
var groupTable = $('#group');
for(var i = 1 ;i <= group.length;i++){
var item = group[i-1]
groupTable.append('<tr> ' +
'<td class="tdClass">' + i + '</td>' +
'<td class="tdClass">' + item.name + '</td>' +
'<td class="tdClass">' + item.num + '</td>' +
'</tr>')
}
var groupTable = $('#alone');
for(var i = 1 ;i <= group.length;i++){
var item = group[i-1]
groupTable.append('<tr> ' +
'<td class="tdClass">' + i + '</td>' +
'<td class="tdClass">' + item.name + '</td>' +
'<td class="tdClass">' + item.num + '</td>' +
'</tr>')
}
在动态添加了元素之后,显示如下图:
上一篇: JQuery实现对html结点的操作(创建,添加,删除)
下一篇: 动态添加HTML代码