.html中的DOM结构 Theres .js和bootstr容器用于制作时尚的画廊。
<script src="main.js"></script>
<div class="container-fluid" id="gal">
<div class="row">
<div class="col-md-offset-2 col-md-8 col-sm-offset-1 col-sm-10 col-xs-12">
<div class="container-fluid galbody" id="gallery3">
<h2 id="galhead">Gallery</h2>
<div id="col1">
</div>
<div id="col2">
</div>
<div id="col3">
</div>
</div>
<div class="container-fluid galbody" id="gallery2">
<div id="col1">
</div>
<div id="col2">
</div>
</div>
<div class="container-fluid galbody" id="gallery1">
<div id="col1">
</div>
</div>
</div>
</div>
</div>
我试图在.js函数和方法中插入数组arr [] urls中的图像。 有一个main.js代码:
document.write("hey!");
//definin' width of browser workspace
var galdiv3 = document.getElementById("gallery3").className = "none";
var galdiv2 = document.getElementById("gallery2").className = "none";
var galdiv1 = document.getElementById("gallery1").className = "none";
//creating array of future gallerydir images paths list
var arr = [];
//creating async flow for read json with paths. after calling back func for parse read text as array list in array (arr)
fs.readFile("gallist.json", function cb(err,rd){
var imgList = JSON.parse(rd);
imgList.forEach(function(file) {
arr += file + ", ";
}, this);
console.log(arr);
});
function singleGrid()
{
galdiv1.removeAttribute(className = " none");
function imgFill(){
for (var file in arr){
var x = document.createElement("div");
x.className();
}
}
imgFill();
}
singleGrid();
问题在于:
var galdiv3 = document.getElementById("gallery3")**.className = "none"**;
var galdiv2 = document.getElementById("gallery2")**.className = "none"**;
var galdiv1 = document.getElementById("gallery1")**.className = "none"**;
控制台抛出错误&#34;未捕获的TypeError:无法设置属性&#39; className&#39; of null&#34;
答案 0 :(得分:1)
您尝试在将DOM元素插入页面之前尝试访问它们。
所以在表达式中
var galdiv3 = document.getElementById("gallery3").className = "none";
表达式document.getElementById("gallery3")
返回null。结果:null.className
抛出了错误。
这是因为<script></script>
标记在添加到页面的那一刻,即在加载页面期间,在添加其他标记之前执行其内容。为此,当执行脚本时,页面中没有其他元素,因此您无法找到它们。
将<script src="main.js"></script>
移到底部,或者只是将所有代码放在window.onload
事件中。