2 回答

TA貢獻1797條經驗 獲得超4個贊
您可以使用查詢字符串.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
僅應用于構造新數組。如果您不打算構造新數組,請使用其他數組。對于副作用(例如附加偵聽器),請使用forEach
或for
循環。

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