javascript操作向表格中動(dòng)態(tài)加載數(shù)據(jù)
本文實(shí)例為大家分享了javascript實(shí)現(xiàn)向表格中動(dòng)態(tài)加載數(shù)據(jù)的具體代碼,供大家參考,具體內(nèi)容如下
首先在HTML中編寫表格信息
<table width="500px" border="1"> //表格頭部信息 <thead> <tr> <th>編號</th> <th>姓名</th> <th>身份</th> <th>操作</th> </tr> </thead> //表格內(nèi)容信息 <tbody id="tbBody"></tbody> </table>
然后編寫js代碼
<!--script中的type默認(rèn)為"text/javascript"--> <script type="text/javascript"> //創(chuàng)建一個(gè)數(shù)組 var per=[ {id:'001',name:'張三',job:'學(xué)生'}, {id:'002',name:'張三',job:'學(xué)生'}, {id:'003',name:'張三',job:'學(xué)生'}, {id:'004',name:'張三',job:'學(xué)生'} ]; //打開窗口就執(zhí)行 window.onload=function () { var tbody=document.getElementById('tbBody'); for(var i=0;i<per.length;i++){ var trow=getDataRow(per[i]); tbody.appendChild(trow) } } //獲取數(shù)據(jù) function getDataRow(h) { //創(chuàng)建行 var row=document.createElement('tr'); /*創(chuàng)建第一列id屬性*/ //創(chuàng)建第一列id var idCell=document.createElement('td'); //向id填充數(shù)據(jù) idCell.innerText=h.id; //加入行 row.appendChild(idCell); /*創(chuàng)建第二列屬性name 和上面類似*/ var nameCell=document.createElement('td'); nameCell.innerText=h.name; row.appendChild(nameCell); /*創(chuàng)建第三列屬性job 和上面類似*/ var jobCell=document.createElement('td'); jobCell.innerText=h.job; row.appendChild(jobCell); //到這里,json中的數(shù)據(jù)已經(jīng)添加到表格里面了,下面為每行末尾添加刪除按鈕 /*創(chuàng)建第四列屬性 刪除屬性*/ var deleteCell=document.createElement('td'); //加入行 row.appendChild(deleteCell); //創(chuàng)建一個(gè)刪除按鈕控件 var buttonCell=document.createElement('input'); //setAttribute()方法創(chuàng)建或改變某個(gè)新屬性,如果指定屬性已存在,則只設(shè)置該值 buttonCell.setAttribute('type','button'); buttonCell.setAttribute('value','刪除'); //刪除功能 buttonCell.onclick=function () { if(confirm("確定刪除這一行嗎?")){ //找到按鈕所在的行之后進(jìn)行刪除 parentNode節(jié)點(diǎn)查找 this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode); } } //吧刪除按鈕控件加入第四列屬性 刪除屬性 deleteCell.appendChild(buttonCell); //返回行的數(shù)據(jù) return row; } </script>
下面是操作后的顯示圖
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
javascript中mouseover、mouseout使用詳解
這篇文章主要介紹了javascript中mouseover、mouseout使用詳解的相關(guān)資料,需要的朋友可以參考下2015-07-07JavaScript中擴(kuò)展Array contains方法實(shí)例
這篇文章主要介紹了JavaScript中擴(kuò)展Array contains方法實(shí)例,本文直接給出實(shí)現(xiàn)代碼,需要的朋友可以參考下2015-03-03JavaScript中callee和caller的區(qū)別與用法實(shí)例分析
這篇文章主要介紹了JavaScript中callee和caller的區(qū)別與用法,結(jié)合實(shí)例形式分析了javascript中callee和caller的功能、區(qū)別、用法及操作注意事項(xiàng),需要的朋友可以參考下2019-06-06微信小程序?qū)崿F(xiàn)兩邊小中間大的輪播效果的示例代碼
這篇文章主要介紹了微信小程序?qū)崿F(xiàn)兩邊小中間大的輪播效果的示例代碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-12-12JavaScript學(xué)習(xí)筆記之?dāng)?shù)組的增、刪、改、查
這篇文章主要介紹了JavaScript學(xué)習(xí)筆記之?dāng)?shù)組的增、刪、改、查的相關(guān)資料,需要的朋友可以參考下2016-03-03注意 JavaScript 中 RegExp 對象的 test 方法
注意 JavaScript 中 RegExp 對象的 test 方法...2007-01-01