首页 > 代码库 > 表格操作练习

表格操作练习

<!DOCTYPE HTML><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>无标题文档</title><script>window.onload = function(){    var data = [        {id:1,name:leo,sex:},        {id:2,name:tom,sex:},        {id:3,name:cherry,sex:},        {id:4,name:jack,sex:}    ];    var tab = document.getElementById(table1),        df = document.createDocumentFragment(),        tb = tab.tBodies[0];        var resetColor = function(){        for(var y=0;y<tb.rows.length;y++){            if(y%2 == 0)                tb.rows[y].style.background = #e0e0e0;            else                tb.rows[y].style.background = #fff;        }    };        var createTd = function(elem,html){        var td = document.createElement(td);        td.innerHTML = html;        elem.appendChild(td);        return td;    };        if(!tb){        tb = document.createElement(tbody);        tab.appendChild(tb);    }        for(var i in data){        var tr = document.createElement(tr),            td;                    createTd(tr,data[i].id);        createTd(tr,data[i].name);        createTd(tr,data[i].sex);                td = createTd(tr,<a href="javascript:;">删除</a>);        (td.firstElementChild || td.firstChild).onclick = function(){            tb.removeChild(this.parentNode.parentNode);            resetColor();        };                if(i%2==0) tr.style.background = #e0e0e0;        df.appendChild(tr);    }    tb.appendChild(df);};</script></head><body><table id="table1" width="100%" border="1px">    <thead>        <tr>            <th>编号</th>            <th>姓名</th>            <th>性别</th>            <th>操作</th>        </tr>    </thead></table></body></html>

效果:

技术分享

表格操作练习