js動態(tài)生成表格(節(jié)點操作)
更新時間:2021年01月12日 17:21:57 作者:劉劉劉code
這篇文章主要為大家詳細介紹了js動態(tài)生成表格,進行節(jié)點操作,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了js動態(tài)生成表格的具體代碼,供大家參考,具體內(nèi)容如下
針對DOM節(jié)點操作,該案例效果圖如下(代碼量不多,就沒有結構與行為相分離):

原生js實現(xiàn)(注釋里面解釋了做法):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
table {
width: 500px;
margin: 100px auto;
border-collapse: collapse;
text-align: center;
}
td,
th {
border: 1px solid #333;
}
thead tr {
height: 40px;
background-color: #ccc;
}
</style>
</head>
<body>
<table cellspacing="0">
<thead>
<tr>
<th>姓名</th>
<th>科目</th>
<th>成績</th>
<th>操作</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
<script type="text/javascript">
//因為里面的學生數(shù)據(jù)都是動態(tài)的,我們需要js動態(tài)生成 這里我們需要模擬數(shù)據(jù),自己定義好數(shù)據(jù)
// 數(shù)據(jù)我們采取對象形式儲存
//1 先準備好學生的數(shù)據(jù)
//2 所有數(shù)據(jù)都是放到tbody里面(多少人,多少行)
var datas = [{
name: '劉舒新',
subject: 'JavaScript',
score: '100'
}, {
name: '宋祥隆',
subject: 'JavaScript',
score: '80'
},
{
name: '崔健',
subject: 'JavaScript',
score: '90'
},
{
name: '郄海淼',
subject: 'JavaScript',
score: '70'
}
];
//console.log(datas.length);
var tbody = document.querySelector('tbody');
for (var i = 0; i < datas.length; i++) {
//創(chuàng)建行
trs = document.createElement('tr');
tbody.appendChild(trs);
//創(chuàng)建單元格 td的數(shù)量取決于每個對象里面的屬性個數(shù)
for(var k in datas[i]){
//創(chuàng)建單元格
var td=document.createElement('td');
//把對象里面的屬性值 給td
//console.log(datas[i][k]);
td.innerHTML=datas[i][k];
trs.appendChild(td);
}
//創(chuàng)建操作刪除單元格
var td=document.createElement('td');
td.innerHTML='<a href="javascript:;" rel="external nofollow" >刪除</a>'
trs.appendChild(td);
}
//刪除操作
var a=document.querySelectorAll('a');
for(var i=0;i<a.length;i++){
a[i].onclick=function(){
tbody.removeChild(this.parentNode.parentNode);
}
}
</script>
</html>
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:
- js生成動態(tài)表格并為每個單元格添加單擊事件的方法
- JS實現(xiàn)動態(tài)生成html table表格的方法分析
- JS實現(xiàn)動態(tài)生成表格并提交表格數(shù)據(jù)向后端
- JS控制網(wǎng)頁動態(tài)生成任意行列數(shù)表格的方法
- js動態(tài)生成指定行數(shù)的表格
- 用js實現(xiàn)的一個根據(jù)內(nèi)容自動生成表格的函數(shù)
- 基于JavaScript代碼實現(xiàn)自動生成表格
- 用js+xml自動生成表格的東西
- 用按鈕觸發(fā)Javascript動態(tài)生成一個表格的代碼
- Nodejs獲取網(wǎng)絡數(shù)據(jù)并生成Excel表格
相關文章
一文搞懂JSON(JavaScript Object Notation)
Json 有兩種基本的結構,即 Json對象 和 Json 數(shù)組。通過 Json 對象和 Json 數(shù)組這兩種結構的組合可以表示各種復雜的結構,今天通過本文給大家介紹JavaScript Object Notation的基本知識,感興趣的朋友一起看看吧2021-10-10

