<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <style> div { width: 300px; height: 300px; border: 1px solid pink; } </style> </head> <body> <input type="button" value="创建表格" id="bt"/> <div id="dv"></div> <script src="common.js"></script> <script> var arr = [ {name: "百度", href: "http://www.baidu.com"}, {name: "京东", href: "http://www.jd.com"}, {name: "淘宝", href: "http://www.taobao.com"}, {name: "优酷", href: "http://www.youku.com"}, {name: "爱奇艺", href: "http://www.aiqiyi.com"} ]; my$("bt").onclick = function () { //创建table加入到div中 var tableObj = document.createElement("table"); tableObj.border = "1"; tableObj.cellPadding = "0"; tableObj.cellSpacing = "0"; my$("dv").appendChild(tableObj); //创建行,把行添加到table中 for (var i = 0; i < arr.length; i++) { //每个对象 var td = arr[i]; var trObj = document.createElement("tr"); tableObj.appendChild(trObj); //创建第一个列,然后加入到行中 var td1 = document.createElement("td"); td1.innerText = arr[i].name; trObj.appendChild(td1); //创建第二个列,然后加入到行中 var td2 = document.createElement("td"); td2.innerHTML = "<a href=" + arr[i].href + ">" + arr[i].name + "</a>" trObj.appendChild(td2); } }; </script> </body> </html>
原文地址:https://www.cnblogs.com/cuilichao/p/9383112.html
时间: 2024-10-08 13:32:18