请解释为什么不起作用.className属性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[]url中的图像。有一个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"**;

控制台抛出错误"Uncaught TypeError:无法设置属性"className"为null">

您试图在DOM元素插入页面之前访问它们。

因此在表达式中

var galdiv3 = document.getElementById("gallery3").className = "none";

则表达式CCD_ 1返回null。结果:null.className抛出错误。

之所以会发生这种情况,是因为<script></script>标记在将其内容添加到页面的那一刻执行其内容,也就是说,在加载页面期间,在添加其他标记之前。为此,在执行脚本时,页面中没有其他元素,因此无法找到它们。

<script src="main.js"></script>移到底部,或者简单地将所有代码放在window.onload事件中。

最新更新