gpt4 book ai didi

Javascript:AppendChild

转载 作者:数据小太阳 更新时间:2023-10-29 04:21:58 24 4
gpt4 key购买 nike

我正在学习 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。我做错了什么?

最佳答案

尝试将您的 JavaScript 包装在 onload 函数中。所以首先添加:

<body onload="load()">

然后将你的 javascript 放在加载函数中,所以:

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);
}

关于Javascript:AppendChild,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6867003/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com