我只是想問如何在javascript中使用“getElementsByClassName()方法”更改或顯示不同的顏色,所以在這里我想從“ex”類中更改免費的藍色,并從“example”類中更改為紅色,但它沒有作業。
<!DOCTYPE html>
<html>
<head>
<style>
.example {
border: 1px solid black;
padding 8px;
}
</style>
</head>
<body>
<h1>The Document Object</h1>
<h2>The getElementsByClassName() Method</h2>
<p>Change the background color of all elements with :</p>
<div class="example">
A div with
</div>
<br>
<div class="ex">
A div with
</div>
<p class="example">
A p element with .
</p>
<p class="ex">
A p element with .
</p>
<p>A <span class="example">span</span> element with .</p>
<script>
const collection = document.getElementsByClassName("example");
for (let i = 0; i < collection.length; i ) {
collection[i].style.backgroundColor = "red";
}
const collection = document.getElementsByClassName("ex");
for (let i = 0; i < collection.length; i ) {
collection[i].style.backgroundColor = "blue";
}
</script>
</body>
</html>
uj5u.com熱心網友回復:
您的代碼作業正常,但您有兩個變數,其名稱為collectionrename 其中一個
<!DOCTYPE html>
<html>
<head>
<style>
.example {
border: 1px solid black;
padding 8px;
}
</style>
</head>
<body>
<h1>The Document Object</h1>
<h2>The getElementsByClassName() Method</h2>
<p>Change the background color of all elements with :</p>
<div class="example">
A div with
</div>
<br>
<div class="ex">
A div with
</div>
<p class="example">
A p element with .
</p>
<p class="ex">
A p element with .
</p>
<p>A <span class="example">span</span> element with .</p>
<script>
const collection = document.getElementsByClassName("example");
for (let i = 0; i < collection.length; i ) {
collection[i].style.backgroundColor = "red";
}
const collection2 = document.getElementsByClassName("ex");
for (let i = 0; i < collection2.length; i ) {
collection2[i].style.backgroundColor = "blue";
}
</script>
</body>
</html>
uj5u.com熱心網友回復:
“不起作用”是什么意思?是ex藍色的,沒有顏色的example嗎?沒有顏色嗎?
嘗試檢查控制臺中的輸出(開發人員工具 - F12)。我確信您會在使用您的代碼段時收到錯誤,因為您重新定義了collection兩次變數。如果您計劃使用在分配后更改變數值的解決方案,請使用let而不是。const或者,為您的第二個 for 回圈定義另一個變數。
如果您仍然不確定,這是您更正的代碼段:
let collection = document.getElementsByClassName("example");
for (let i = 0; i < collection.length; i ) {
collection[i].style.backgroundColor = "red";
}
collection = document.getElementsByClassName("ex");
for (let i = 0; i < collection.length; i ) {
collection[i].style.backgroundColor = "blue";
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/494415.html
標籤:javascript jQuery 节点.js Vue.js
