我正在尝试创建跨度并将分割字符串作为每个跨度内的字符附加。因此,考虑到下面的消息,它会类似于 <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)
最佳答案
尝试将 JavaScript 放在底部(body
标记下方或内部的任意位置)。
或者如果您没有 jQuery,请使用它:
document.addEventListener("DOMContentLoaded", function(event) {
//do work
});
或者如果你有 jQuery :
$( document ).ready(function() {
//do work
});
调用 scramble()
时,document.body
仍然不存在。
引用文献:
关于javascript - 创建跨度并附加文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28733123/