4 回答

TA貢獻(xiàn)1946條經(jīng)驗(yàn) 獲得超3個(gè)贊
我要補(bǔ)充一點(diǎn),如果選擇器僅由一個(gè)元素使用,最好分配一個(gè) id 并使用 getElementById。
let boxOne = document.getElementById("one");
let allBoxes = document.getElementsByClassName("square");
boxOne.onclick = function() {
alert("Clicked via ID");
}
const arr = [1, 2, 3];
arr.forEach(i => {
allBoxes[i].onclick = function() {
alert("Clicked via Class");
}
})
.square {
width: 100px;
height: 100px;
background: blue;
margin: 20px;
font-size: 50px;
color: white;
text-align: center;
display: flex;
flex-direction: column;
justify-content: center;
cursor: pointer;
}
<body>
<div class="container">
<div class="square" id="one">
1
</div>
<div class="square" id="two">
2
</div>
<div class="square" id="three">
3
</div>
<div class="square" id="four">
4
</div>
</div>
</body>

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超9個(gè)贊
文檔。
getElementsByClassName 返回具有該類名的元素?cái)?shù)組(不帶點(diǎn))
querySelector 用于 css 選擇器(例如“.one”、“div.one”)
querySelectorAll 像 2. 但返回?cái)?shù)組

TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超8個(gè)贊
let boxOne = document.getElementsByClassName("one")[0]
boxOne.onclick = function() {
alert("Clicked!")
}
div {
width: 100px;
height: 100px;
margin: 30px;
background: blue
}
<body>
<div class="container">
<div class="one">
</div>
<div class="two">
</div>
<div class="three">
</div>
<div class="four">
</div>
</div>
<script src="script.js"></script>
</body>

TA貢獻(xiàn)1799條經(jīng)驗(yàn) 獲得超9個(gè)贊
使用此行:document.getElementsByClassName(".one")[0]
您已經(jīng)針對(duì) div,因此將其更改 boxOne[0].onclick =
為: boxOne.onclick =
添加回答
舉報(bào)