动态通过js脚本构造html页面


下面的例子是使用jquery,实现动态构造html页面的代码

<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Personal Information</title>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script> 
  
<script type="text/javascript" language="javascript">
    //动态添加表格的行数
    $(function()
    {
        var i=0;
        for(i=0;i<100;i++)//这里循环100次
        {
           $("<tr />").append("<td>陈希章</td><td>100< /td>").appendTo("#contents");//每一次都增加一个tr的标记,里面包含两个td标记,最后将其追加到表格中去(通过id定位)
        }
    });
</script> 
</head> 
<body>
<table id="contents">
    <tr>
        <th>姓名</th>
        <th>年龄</th>
    </tr>
</table> 
</body> 
</html> 

  运行起来的效果如下

  这样看起来很不错的, 但如果那个行比较复杂,则构造起来挺麻烦的。我们还可以利用模板的方式来做,如下

<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Personal Information</title>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script> 
<script type="text/javascript" language="javascript">
    //动态添加表格的行数
    $(function()
    {
        var i=0;
        for(i=0;i<100;i++)
        {
            //$("<tr />").append("<td>陈希章</td><td>100</td>").appendTo("#contents");
           var row=$("#template").clone();//从模板复制一行
            row.find("#name").text("陈希章");
            row.find("#age").text("100");
            row.attr("id","data");
            row.appendTo("#contents");
        }
    }); 
</script> 
</head> 
<body>
<table id="contents">
    <tr>
        <th>姓名</th>
        <th>年龄</th>
    </tr>
    <tr id="template">
        <td id="name"></td>
        <td id="age"></td>
    </tr>
</table> 
</body> 
</html> 


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3