java前端javascript生成動態(tài)表格示例演示
前言
動態(tài)生成表格是前端開發(fā)中非常重要的內(nèi)容,常常是后端返回數(shù)據(jù)(大多是json類型),我們前端通過js循環(huán)來動態(tài)添加,所以這部分內(nèi)容是十分重要的,今天我就來寫寫這部分內(nèi)容,其實也很簡單的,仔細(xì)看哦?。?!
案例分析
因為里面的學(xué)生數(shù)據(jù)都是動態(tài)的,我們需要 js 動態(tài)生成。這里我們模擬數(shù)據(jù),自己定義好數(shù)據(jù)。數(shù)據(jù)我們采取對象形式存儲。所有的數(shù)據(jù)都是放到 tbody 里面的行里面。因為行很多,我們需要循環(huán)創(chuàng)建多個行(對應(yīng)多少人)。
代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
table{
width: 400px;
border-collapse: collapse;
margin: 100px auto;
border: 1px solid #888;
text-align: center;
}
th,td{
border: 1px solid #888;
padding: 5px 0px;
}
th{
background-color: skyblue;
}
tr:hover{
cursor: default;
background-color: pink;
}
a:hover{
cursor: pointer;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<th>姓名</th>
<th>科目</th>
<th>成績</th>
<th>操作</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
//動態(tài)生成表格
//data是模擬的后臺傳來的數(shù)據(jù)
var data = [
{
"name" :"我是阿牛",
"class":"javascript",
"grade": 100
},
{
"name" :"別搞我啊",
"class":"javascript",
"grade": 99
},
{
"name" :"我不懂細(xì)節(jié)",
"class":"javascript",
"grade": 98
},
{
"name" :"她說不合適",
"class":"javascript",
"grade": 96
},
{
"name" :"神明也無光",
"class":"javascript",
"grade": 95
}
];
var tbody = document.querySelector('tbody');
for(var i=0;i<data.length;i++){
var tr = document.createElement('tr'); //創(chuàng)建行
tbody.appendChild(tr); // 將tr放到tbody里
for (var k in data[i]){
var td = document.createElement('td'); //創(chuàng)建列
td.innerHTML = data[i][k]; //單元格(列)添加數(shù)據(jù)
tr.appendChild(td); //將td放到tr里
}
//創(chuàng)建刪除的單元格
var td = document.createElement('td');
td.innerHTML = '<a herf="javascript:;" style="color:blue;">' + '刪除' + '</a>';
tr.appendChild(td);
}
//實現(xiàn)點擊刪除兩字刪除對應(yīng)的行
var as = document.querySelectorAll('a');
for (var i=0;i<as.length;i++){
as[i].onclick = function(){
tbody.removeChild(this.parentNode.parentNode); //this.parentNode.parentNode 代表a的父親的父親
}
}
</script>
</body>
</html>
動圖演示

結(jié)語
陸陸續(xù)續(xù)寫了很多前端基礎(chǔ)知識和小demo了,這些對初學(xué)者都很有用,我把他們都放在我的專欄里了,精心打造了軟磨硬泡系列,一起來學(xué)習(xí)吧!
以上就是java前端javascript生成動態(tài)表格示例演示的詳細(xì)內(nèi)容,更多關(guān)于java前端javascript生成動態(tài)表格的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
bootstrap模態(tài)框遠(yuǎn)程示例代碼分享
這篇文章主要為大家詳細(xì)介紹了bootstrap模態(tài)框遠(yuǎn)程示例代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-05-05
javascript showModalDialog 多層模態(tài)窗口實現(xiàn)頁面提交及刷新的代碼
javascript 多層模態(tài)窗口showModalDialog頁面提交及刷新2009-11-11

