在Table标签下appendChild()动态添加tr时,使用不是将tr直接加到TBody里.
而是先动态加载TBody,等TBody加载完以后再去加载appendChild命令添加的动态tr标签.
这样就会出现IE浏览器解析不出我们想要的结果.解决方法是:tab.tBody[0].appendChild(tr)(tab为Table的id得到的对象,tr为你动态创建的对象!)
例子:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>DynamicTable.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
<script type="text/javascript">
function creatTable(){
var links = {"百度":"www.baidu.com","新浪":"www.sina.com","人人":"www.renren.com"};
var tab = document.getElementById("tab");
for(var key in links){
/*var link = links[key];
var tr = document.createElement("tr");
var tdName = document.createElement("td");
tdName.innerText = key;
var tdHref = document.createElement("td");
tdHref.innerHTML = "<a href='"+links[key]+"'>"+links[key]+"</a>";
tr.appendChild(tdName);
tr.appendChild(tdHref); IE下不支持appendChild(),IE是把动态的东西加到Tbody里,所以解析错误!
tab.appendChild(tr);*/
/* var link = links[key];
var tr = tab.insertRow();
var tdName = tr.insertCell();
tdName.innerText = key; 仅IE好用,FireFox 不怎么支持!!!
var tdHref = tr.insertCell();
tdHref.innerHTML = "<a href='"+links[key]+"'>"+links[key]+"</a>";*/
var link = links[key];
var tr = document.createElement("tr");
var tdName = document.createElement("td");
tdName.innerText = key;
var tdHref = document.createElement("td");
tdHref.innerHTML = "<a href='"+links[key]+"'>"+links[key]+"</a>";
tr.appendChild(tdName);
tr.appendChild(tdHref);
tab.tBodies[0].appendChild(tr)
}
}
</script>
</head>
<body>
This is my HTML page.
<br>
<table id="tab"></table>
<input type="button" value="创建Table" onclick="creatTable()" />
</body>
</html>
分享到:
评论