Javascript:DOM表格操作

來源:互聯網
上載者:User

標籤:

需求說明:

/**需求說明:*擷取元素:tBodies,tHead,tFoot,rows,cells*表格的建立*資料添加*隔行變色*刪除操作,剩餘表格重新計算,實現隔行變色 */

 

HTML:

<table id="table1">    <tbody>    <tr>    <th>編號</th>    <th>姓名</th>    <th>性別</th>    <th>操作</th>    </tr></tbody></table>

 

CSS:

 

    table{    border:1px solid #eee;    border-collapse: collapse;    }    td,th{  border: 1px solid #eee;  padding: 12px 18px;    }    a{  text-decoration: none;  padding: 4px 10px;  color: #f8f8f8;  font-size: 12px;  border-radius: 3px;  letter-spacing: 2px;  text-shadow: 0 0 1px rgba(0,0,0,.15);  background-color: #eb4f38;    }

 

 

JAVASCRIPT:

 

/**需求說明:*擷取元素:tBodies,tHead,tFoot,rows,cells*表格的建立*資料添加*隔行變色*刪除操作,剩餘表格重新計算,實現隔行變色 *//*=========================*tHead:表格頭*tBodies:表格本文*tFoot:表格尾*rows:行* cells:列========================= */var oTable=document.getElementById(‘table1‘);var oTbody=oTable.tBodies[0];var data=[    {‘id‘:1,‘name‘:‘kevin1‘,‘sex‘:‘男‘},    {‘id‘:2,‘name‘:‘kevin2‘,‘sex‘:‘男‘},    {‘id‘:3,‘name‘:‘kevin3‘,‘sex‘:‘男‘},    {‘id‘:4,‘name‘:‘kevin4‘,‘sex‘:‘男‘},    {‘id‘:5,‘name‘:‘kevin5‘,‘sex‘:‘男‘},    {‘id‘:6,‘name‘:‘kevin6‘,‘sex‘:‘男‘}, ];for(var i=0;i<data.length;i++){var oTr=document.createElement(‘tr‘);    /*添加id*/var oTd=document.createElement(‘td‘);oTd.innerHTML=data[i].id;oTr.appendChild(oTd);/*隔行換色*/        if (i%2===0) {    oTr.style.backgroundColor=‘#fff‘;    }else{    oTr.style.backgroundColor=‘#f8f8f8‘;    } /*添加name*/oTd=document.createElement(‘td‘);oTd.innerHTML=data[i].name;oTr.appendChild(oTd); /*添加sex*/    oTd=document.createElement(‘td‘);oTd.innerHTML=data[i].sex;oTr.appendChild(oTd); /*添加操作*/oTd=document.createElement(‘td‘);/*oTd.innerHTML=‘刪除‘;*/oTr.appendChild(oTd);     /*刪除*/    var oA=document.createElement(‘a‘);    oA.innerHTML=‘刪除‘;    oA.href=‘javascript:‘;
oA.onclick=function(){

//刪除當前【行】 oTbody.removeChild(this.parentNode.parentNode); //刪除操作完成之後,剩餘表格重新計算,實現隔行變色 for(var i=0;i<oTbody.rows.length;i++){ if (i%2===0) { oTbody.rows[i].style.backgroundColor=‘#fff‘; }else{ oTbody.rows[i].style.backgroundColor=‘#f8f8f8‘; } } } oTd.appendChild(oA); oTbody.appendChild(oTr);}

 

  

線上示範:

http://codepen.io/anon/pen/BNJdBY

 

Javascript:DOM表格操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.