首页 > 代码库 > dom 表格操作

dom 表格操作

<!doctype html><html><head><meta charset="utf-8"><title>无标题文档</title><script>window.onload = function (){    var data =http://www.mamicode.com/ [        {name:‘小红‘,age:‘26‘,sex:‘女‘},        {name:‘圆圆‘,age:‘26‘,sex:‘男‘},        {name:‘小吕‘,age:‘21‘,sex:‘女‘},        {name:‘小明‘,age:‘30‘,sex:‘女‘},    ];        var otab = document.getElementById(‘tab1‘);    var otbody = otab.tBodies[0];        for( var i = 0; i < data.length; i++)    {        var otr = document.createElement(‘tr‘);        if( i % 2)        {            otr.style.background = ‘#fff‘;        }        else        {            otr.style.background = ‘pink‘;        }                var otd = document.createElement(‘td‘);        otd.innerHTML = data[i].name;        otr.appendChild(otd);                var otd = document.createElement(‘td‘);        otd.innerHTML = data[i].age;        otr.appendChild(otd);                var otd = document.createElement(‘td‘);        otd.innerHTML = data[i].sex;        otr.appendChild(otd);                var otd = document.createElement(‘td‘);        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)                {                    otr.style.background = ‘#fff‘;                }                else                {                    otr.style.background = ‘pink‘;                }            }        }        otd.appendChild(oa);        otbody.appendChild(otr);                    }}</script></head><body><table border="1" id="tab1" >     <thead>        <tr>            <td>姓名</td>            <td>年龄</td>            <td>性别</td>            <td>备注</td>        </tr>    </thead>     <tbody>    </tbody></table></body></html>

 

dom 表格操作