码迷,mamicode.com
首页 > 其他好文 > 详细

表格操作练习

时间:2016-09-05 01:26:45      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:

<!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>

效果:

技术分享

表格操作练习

标签:

原文地址:http://www.cnblogs.com/gongshunkai/p/5840783.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!