【发布时间】:2015-02-26 10:15:41
【问题描述】:
我正在尝试创建跨度并将拆分字符串附加为每个跨度中的字符。因此,鉴于下面的消息,它会类似于 <span>t</span><span>h</span> 等...
由于某种原因,我在附加到文档正文时收到此错误。为什么?
Uncaught TypeError: Cannot read property 'appendChild' of null
<!doctype html>
<html>
<head>
<script type="text/javascript">
scramble();
function scramble () {
var message = "this is a message";
for (var i = 0; i < message.split("").length; i++) {
var letter = document.createElement('span');
letter.innerHTML = message.split("")[i];
document.body.appendChild(letter);
//document.getElementById("body").appendChild(letter);
}
}
function log (w) {
console.log(w);
}
</script>
</head>
<body>
</body>
</html>
我也试过document.getElementById("body").appendChild(letter);,但同样的错误。
堆栈跟踪:
Uncaught TypeError: Cannot read property 'appendChild' of null
myFunc
(anonymous function)
【问题讨论】:
-
我在 jsfiddle 中试过,效果很好
-
是的^那个。你用的是什么浏览器?
-
铬。我在上面添加了更多
-
您能否发布完整的示例代码(html 和 js)来展示您所描述的问题?
-
@ChrisPietschmann 在上面添加
标签: javascript html