gpt4 book ai didi

javascript - 请解释为什么 .className 属性不起作用?

转载 作者:行者123 更新时间:2023-12-03 03:05:40 24 4
gpt4 key购买 nike

.html 中的 DOM 结构有 .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"**;

控制台抛出错误“未捕获类型错误:无法将属性“className”设置为 null”

最佳答案

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

表达式中的so

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

表达式document.getElementById("gallery3")返回空值。结果:null.className抛出错误。

发生这种情况是因为<script></script>标签在添加到页面时(即在页面加载期间,在添加其他标签之前)执行其内容。为此,当脚本执行时,页面中没有其他元素,因此您无法找到它们。

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

关于javascript - 请解释为什么 .className 属性不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47179821/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com