javascript - Javascript 显示“无法设置属性‘innerHTML’为空”
问题描述
我尝试运行以下显示空白屏幕的代码
function make() {
for (var i = 1; i <= 8; i++) {
var j = "d" + i;
var c = document.createElement("div");
c.setAttribute("id",j);
document.getElementById(j).innerHTML = 'Hello<br>';
}
}
#d1 {font-family: 'Cinzel';}
#d2 {font-family: 'Cookie';}
#d3 {font-family: 'Great Vibes';}
#d4 {font-family: 'Monoton';}
#d5 {font-family: 'Orbitron';}
#d6 {font-family: 'Pacifico';}
#d7 {font-family: 'Righteous';}
#d8 {font-family: 'Sacramento';}
<!DOCTYPE html>
<html>
<head>
<title>Logo</title>
<link href="https://fonts.googleapis.com/css?family=Cinzel|Cookie|Great+Vibes|Monoton|Orbitron|Pacifico|Righteous|Sacramento" rel="stylesheet">
</head>
<body onload="make()">
</body>
</html>
在上面的代码片段中,我使用了一个 javascript 函数,其中我创建了 8 个元素并用 line-break 分隔每个元素。但是,不幸的是,包含“innerHTML”的行会引发类型错误,并且其余代码不会生成所需的输出。
请帮帮我!
谢谢你
解决方案
你错过了这条非常重要的线document.body.appendChild(c);
您必须使用
appendChild
or将元素插入到文档树中,insertBefore
因为在尝试获取元素之前必须将元素插入到 DOM 中document.getElementById(j)
<!DOCTYPE html>
<html>
<head>
<title>Logo</title>
<link href="https://fonts.googleapis.com/css?family=Cinzel|Cookie|Great+Vibes|Monoton|Orbitron|Pacifico|Righteous|Sacramento" rel="stylesheet">
<style type="text/css">
#d1 {
font-family: 'Cinzel';
}
#d2 {
font-family: 'Cookie';
}
#d3 {
font-family: 'Great Vibes';
}
#d4 {
font-family: 'Monoton';
}
#d5 {
font-family: 'Orbitron';
}
#d6 {
font-family: 'Pacifico';
}
#d7 {
font-family: 'Righteous';
}
#d8 {
font-family: 'Sacramento';
}
</style>
</head>
<body onload="make()">
<script type="text/javascript">
function make() {
for (var i = 1; i <= 8; i++) {
var j = "d" + i;
var c = document.createElement("div");
c.setAttribute("id", j);
document.body.appendChild(c);
document.getElementById(j).innerHTML = 'Hello<br>';
}
}
</script>
</body>
</html>
推荐阅读
- ios - Obj-C-点击单元格时向TableView添加新行?
- apache - 禁止访问目录,但不禁止别名?
- reactjs - 根据道具更改反应组件类型
- c++ - 使用共享指针实现单例的正确方法?
- python - 发生异常:错误 mpg123_seek:无效的 RVA 模式。(代码 12)
- rust - 为什么这个 Rust 错误消息谈论数据“流动”?
- c++ - Lambda 函数给出了意外的输出
- vega-lite - 如何在 vega 公式变换中使用阶乘(!)
- javascript - 如何在 v-data-iterator 中获取自定义插槽?
- c++ - 如何正确使用 std::cin.get() 和 std::cin.peek() 的返回值?