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条经验 获得超7个赞
的参数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 关注
- 100 浏览
添加回答
举报