我想在单击 "ALL" h1 元素时切换 .textDecoration class。你能帮我看这段代码吗?
I want to toggle .textDecoration class when I am clicking on "ALL" h1 elements. Can you Help me with this Code?
我只能访问 h1 中的第一个元素。我还可以创建一个按钮并单击循环遍历 h1 元素并打开或关闭 .textDecoration class。但我的目标是一步一步单击我想要的元素并打开或关闭 .textDecoration class.
var x = document.getElementsByTagName("h1")[0];
function myFunction() {
x.classList.toggle("textDecoration");
}
x.addEventListener("click", myFunction);
.textDecoration {
text-decoration: line-through;
}
<h1>Text-Decoration: line-through</h1>
<h1>Text-Decoration: line-through</h1>
<h1>Text-Decoration: line-through</h1>
<h1>Text-Decoration: line-through</h1>
我建议你委派
document.getElementById("container").addEventListener("click", function(e) {
const tgt = e.target.closest("h1");
if (tgt) tgt.classList.toggle("textDecoration");
})
.textDecoration {
text-decoration: line-through;
}
<div id="container">
<h1>Text-Decoration: line-through</h1>
<h1>Text-Decoration: line-through</h1>
<h1>Text-Decoration: line-through</h1>
<h1>Text-Decoration: line-through</h1>
</div>
你的问题在我看来很糟糕,你在找那个吗?
document.querySelectorAll('h1').forEach( (Hn,_,All_h1) =>
{
Hn.onclick =_=>
{
if (Hn.classList.toggle('textDecoration'))
All_h1.forEach( Hx=> Hx.classList.toggle('textDecoration', Hn===Hx) )
}
})
.textDecoration {
text-decoration: line-through;
}
<h1>Text-Decoration: line-through</h1>
<h1>Text-Decoration: line-through</h1>
<h1>Text-Decoration: line-through</h1>
<h1>Text-Decoration: line-through</h1>
我只能访问 h1 中的第一个元素。我还可以创建一个按钮并单击循环遍历 h1 元素并打开或关闭 .textDecoration class。但我的目标是一步一步单击我想要的元素并打开或关闭 .textDecoration class.
var x = document.getElementsByTagName("h1")[0];
function myFunction() {
x.classList.toggle("textDecoration");
}
x.addEventListener("click", myFunction);
.textDecoration {
text-decoration: line-through;
}
<h1>Text-Decoration: line-through</h1>
<h1>Text-Decoration: line-through</h1>
<h1>Text-Decoration: line-through</h1>
<h1>Text-Decoration: line-through</h1>
我建议你委派
document.getElementById("container").addEventListener("click", function(e) {
const tgt = e.target.closest("h1");
if (tgt) tgt.classList.toggle("textDecoration");
})
.textDecoration {
text-decoration: line-through;
}
<div id="container">
<h1>Text-Decoration: line-through</h1>
<h1>Text-Decoration: line-through</h1>
<h1>Text-Decoration: line-through</h1>
<h1>Text-Decoration: line-through</h1>
</div>
你的问题在我看来很糟糕,你在找那个吗?
document.querySelectorAll('h1').forEach( (Hn,_,All_h1) =>
{
Hn.onclick =_=>
{
if (Hn.classList.toggle('textDecoration'))
All_h1.forEach( Hx=> Hx.classList.toggle('textDecoration', Hn===Hx) )
}
})
.textDecoration {
text-decoration: line-through;
}
<h1>Text-Decoration: line-through</h1>
<h1>Text-Decoration: line-through</h1>
<h1>Text-Decoration: line-through</h1>
<h1>Text-Decoration: line-through</h1>