【发布时间】:2019-06-12 21:27:18
【问题描述】:
我有以下示例代码。我正在尝试在 javascript 代码中向 id="section" 添加一些类,但未成功。错误:删除注释代码时,无法读取 null 的属性“classList”。任何帮助将不胜感激!
第 1 部分:
var template = document.querySelector('#container').innerHTML;
var contents = '';
var section = document.createElement("div");
// These two lines cause the error
var section = document.getElementById("section");
section.classList.add("bg-yellow");
contents = template.replace(/\{\{title\}\}/, "Title");
section.insertAdjacentHTML('beforeend', contents);
document.getElementById('content').appendChild(section);
第 2 部分:(更新自 Randy Casburn 的原始答案)
var data = [{
"Title": "One"},
{"Title": "Two"},
{"Title": "Three"}];
var template = document.querySelector('#container').innerHTML;
var contents = '';
var section = document.createElement("div");
for(var i = 0; i < data.length; i++){
contents += template.replace(/\{\{title\}\}/, data[i].Title);
}
section.innerHTML = contents;
var innerSection = section.querySelector("#section");
innerSection.classList.add("bg-yellow","blue");
document.getElementById('content').appendChild(section);
.sub-section{
background: tomato;
width: 100px;
}
.bg-yellow{
background: yellow!important;
width: 100%;
height: auto;
}
.blue{
color: blue!important;
}
<div id="content"></div>
<script type="template" id="container">
<div id="section">
<div class="sub-section">
<h1>{{title}}</h1>
</div>
</div>
</script>
【问题讨论】:
-
您是说当您取消注释这些行时会发生错误吗?
-
@MTCoster 是的,没错
-
浏览器会忽略
<script type="template" />块内的所有内容。因此,在将其正确添加到 DOM 之前,您无法对其进行查询。您阅读了它,但从未将其添加到 DOM。 -
你不能把html放在脚本标签里
-
您可以在脚本标签中添加任何您想要的内容,但浏览器会将其解释为纯文本:stackoverflow.com/a/5679857/2831645
标签: javascript html