2 回答

TA貢獻1815條經(jīng)驗 獲得超13個贊
您可以使用查詢字符串.container > .content來匹配具有類名的元素,這些元素是具有類名content的元素的子級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>
另請注意,.map僅應用于構造新數(shù)組。如果您不打算構建一個新數(shù)組,請使用其他東西。對于副作用(如附加偵聽器),請使用forEach或for循環(huán)。

TA貢獻1772條經(jīng)驗 獲得超8個贊
to 的參數(shù)Object.entries()必須是一個對象,而不是一個字符串。您想要的是document.querySelectorAll(),它返回與選擇器匹配的所有元素的列表。由于您要單擊<h3>按鈕,因此需要擴展選擇器以匹配它們。
您還應該使用forEach()而不是map(). map()當您想要返回一個包含在原始數(shù)組上調用函數(shù)的結果的新數(shù)組時使用。如果您只想對數(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>
添加回答
舉報