利用javascript动态创建表格<!--进阶-->

来源:互联网 发布:逸晗网络视频编辑 编辑:程序博客网 时间:2024/05/19 03:27

//说明:实现功能、原理上文相同。不过这次是利用已有的简单的方法创建行和列,并实现内容行鼠标移入变色功能!

效果图:

/*两个方法

1、  trNode  table.insertRow(-1)    利用已创建的表格对象创建一行,返回值为该行的dom对象

2   tdNode trNode.insertCell(-1)    利用已经创建的行对象创建一列,返回值为该列的dom对象

*/

//实现代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>动态创建表格</title>

 <meta http-equiv="content-type" content="text/html;charset=gb2312">
        <style type="text/css">
          caption {
                padding: 0 0 5px 0;
                width: 450px;
                font: italic 11px "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif;
                text-align: right;
                }
        td {
            border:1px solid #c1dad7;   
            padding: 6px 6px 6px 12px;
            color: #4f6b72;
            text-align: center;
            width:150px;
            }
        .thead{
        background-color:#cae8ea;
        }
        </style>
        <script type="text/javascript">
        onload=function(){
            var jsons=[{name:"andy",age:20,gender:"male"},{name:"xiao",age:23,gender:"female"}];//json数组
            
            var table=document.createElement('table');//创建表
            var caption=document.createElement('caption');//创建标题
            caption.innerHTML='学生信息表';//设置标题的内容
            table.appendChild(caption);//将标题加入table
            
            var tHead=table.insertRow(-1);//创建首行
            for(var tHeadContent in jsons[0]){//循环遍历json数组中的第一值,获取每个json对象的键名
                tHead.insertCell(-1).innerHTML=tHeadContent;
            }
            tHead.className='thead';//设置第一行(即列名所在行)所引用的样式名称
            
            for(var i=0;i<jsons.length;i++){//循环遍历json数组
                var tr=table.insertRow(-1);//创建一行
                for(var item in jsons[i]){                
                    var td=tr.insertCell(-1);//每循环一次就创建创建一列
                    td.innerHTML=jsons[i][item];//设置该列的列值    
                }
                    tr.onmouseover=function(){//为每行添加鼠标移入事件
                        this.style.backgroundColor='#8aeebb';
                    };
                    tr.onmouseout=function(){//为每行添加鼠标离开事件
                    this.style.backgroundColor="";
                    };
            }
        
            var body=document.getElementsByTagName('body')[0];//获取body对象
            body.appendChild(table);//将table数组加入到body中
        }
        </script>
    </head>
    <body>
    </body>
</html>

0 0
原创粉丝点击