提问人:theMegaSheep 提问时间:8/31/2023 最后编辑:halfertheMegaSheep 更新时间:8/31/2023 访问量:84
为什么 getElementsByClassName() 不起作用?[复制]
Why does getElementsByClassName() not work? [duplicate]
问:
我正在上 JavaScript 基础课,从第一分钟开始我就无法跟上。这种语言对我来说毫无意义。我得到 HTML 和 CSS,但 JS 对我来说是无稽之谈。
我试图在实践中练习和学习,但我什至无法通过第一行代码。这是我所拥有的:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Buttons</title>
<link rel="stylesheet" href="css/style.css">
<script src = "js/jScript.js"></script>
</head>
<body>
<p><button type="button" class="btn" ></button></p>
<p><button type="button" class="btn" ></button></p>
<p><button type="button" class="btn" ></button></p>
</body>
</html>
/* CSS SHEET */
@charset "UTF-8";
.btn{
width: 10px;
height: 40px;
background: gray;
}
// JAVASCRIPT //
function btnStyle(){
document.getElementsByClassName("btn").style.width="120px";
}
我所要做的就是将所有类为“btn”的按钮更改为 120px 的宽度。根据我有限的理解,这应该有效。我不想要其他方法来完成此操作。我想要解释为什么这不起作用。
答:
2赞
Scott Marcus
8/31/2023
#1
如前所述,在使用元素集合时,除非深入研究该集合,否则无法访问元素的特定实例。这就像拥有一辆老爷车收藏,当你真的想改变一辆车的颜色时,说“把颜色改成蓝色”来指代这个收藏。
接下来,避免使用 .getElementsByClassName()。
这是一种 25+ 年前扫描 DOM 以查找匹配元素集合的方法,但它返回所谓的“实时节点列表”,并且会极大地损害性能。坦率地说,你为学习这个而学习的任何课程都不应该教这个API,你应该让你的教师知道他们正在教过时的东西。
请参阅下面的评论:
// Gather all the elements with a class of "btn" into a collection
// and loop over that collection, one element at a time
document.querySelectorAll(".btn").forEach(function(button){
button.classList.add("width120"); // Apply a pre-existing style
});
@charset "UTF-8";
.btn{
width: 10px;
height: 40px;
background: gray;
}
.width120 { width:120px; }
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Buttons</title>
<link rel="stylesheet" href="css/style.css">
<script src = "js/jScript.js"></script>
</head>
<body>
<p><button type="button" class="btn" ></button></p>
<p><button type="button" class="btn" ></button></p>
<p><button type="button" class="btn" ></button></p>
</body>
</html>
评论
.style
document.getElementByClassName("btn")
.getElementsByClassName()
.querySelectorAll()