我正在学习appendChild,到目前为止我已经想出了这个代码:
var blah = "Blah!";
var t = document.createElement("table"),
tb = document.createElement("tbody"),
tr = document.createElement("tr"),
td = document.createElement("td");
t.style.width = "100%";
t.style.borderCollapse = 'collapse';
td.appendChild(document.createTextNode(blah));
// note the reverse order of adding child
tr.appendChild(td);
tb.appendChild(tr);
t.appendChild(tb);
document.getElementById("theBlah").appendChild(t);<div id="theBlah">d</div>
但这给了我一个错误,即Uncaught TypeError: Cannot call method 'appendChild' of null。我做错了什么?
发布于 2011-07-29 07:34:51
尝试将JavaScript包装在onload函数中。所以首先添加:
<body onload="load()">然后将您的javascript放入load函数,因此:
function load() {
var blah="Blah!";
var t = document.createElement("table"),
tb = document.createElement("tbody"),
tr = document.createElement("tr"),
td = document.createElement("td");
t.style.width = "100%";
t.style.borderCollapse = 'collapse';
td.appendChild(document.createTextNode(blah));
// note the reverse order of adding child
tr.appendChild(td);
tb.appendChild(tr);
t.appendChild(tb);
document.getElementById("theBlah").appendChild(t);
}发布于 2011-07-29 07:41:51
在页面加载完成之前,脚本正在运行。这就是document.getElementById("theBlah")返回null的原因。
可以使用jQuery之类的内容,也可以简单地使用以下内容
<script>
window.onload = function () {
var blah="Blah!";
var t = document.createElement("table"),
tb = document.createElement("tbody"),
...
//the rest of your code here
};
</script>发布于 2011-07-29 07:35:50
问题是document.getElementById("theBlah")返回null。原因是您的代码在theBlah元素创建之前运行。您应该将代码放在onload事件处理程序中。
https://stackoverflow.com/questions/6867003
复制相似问题