2 回答

TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超13個(gè)贊
您可以使用查詢(xún)字符串.container > .content來(lái)匹配具有類(lèi)名的元素,這些元素是具有類(lèi)名content的元素的子級(jí)container:
for (const content of document.querySelectorAll('.Container > .content')) {
content.addEventListener('click', (e) => {
content.style.backgroundColor = 'yellow';
content.children[0].textContent = 'changed text';
console.log("Hello " + content.outerHTML + ")...");
});
}
body {
background-color: rgba(255, 255, 255, 1);
margin: 0px;
padding: 0px;
height: 100vh;
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
overflow: hidden;
}
.Container {
background-color: lightgray;
margin: 0;
padding: 0;
height: auto;
width: 250px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
overflow: hidden;
}
.content {
background-color: lightcyan;
margin: 5px;
padding: 0;
height: auto;
width: 80%;
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
overflow: hidden;
}
h3 {
color: red;
}
<div class="Container">
<div class="content">
<h3>content 1</h3>
</div>
<div class="content">
<h3>content 2</h3>
</div>
<div class="content">
<h3>content 3</h3>
</div>
</div>
另請(qǐng)注意,.map僅應(yīng)用于構(gòu)造新數(shù)組。如果您不打算構(gòu)建一個(gè)新數(shù)組,請(qǐng)使用其他東西。對(duì)于副作用(如附加偵聽(tīng)器),請(qǐng)使用forEach或for循環(huán)。

TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超8個(gè)贊
to 的參數(shù)Object.entries()必須是一個(gè)對(duì)象,而不是一個(gè)字符串。您想要的是document.querySelectorAll(),它返回與選擇器匹配的所有元素的列表。由于您要單擊<h3>按鈕,因此需要擴(kuò)展選擇器以匹配它們。
您還應(yīng)該使用forEach()而不是map(). map()當(dāng)您想要返回一個(gè)包含在原始數(shù)組上調(diào)用函數(shù)的結(jié)果的新數(shù)組時(shí)使用。如果您只想對(duì)數(shù)組元素執(zhí)行操作,則不需要返回新數(shù)組。
document.querySelectorAll('.Container > .content > h3').forEach((element) => {
element.addEventListener("click", function() {
// Output innerHTML of the clicked element
console.log("Hello " + this.innerHTML);
});
});
body {
background-color: rgba(255, 255, 255, 1);
margin: 0px;
padding: 0px;
height: 100vh;
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
overflow: hidden;
}
.Container {
background-color: lightgray;
margin: 0;
padding: 0;
height: auto;
width: 250px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
overflow: hidden;
}
.content {
background-color: lightcyan;
margin: 5px;
padding: 0;
height: auto;
width: 80%;
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
overflow: hidden;
}
h3 {
color: red;
}
<div class="Container">
<div class="content">
<h3>content 1</h3>
</div>
<div class="content">
<h3>content 2</h3>
</div>
<div class="content">
<h3>content 3</h3>
</div>
</div>
添加回答
舉報(bào)