繁体   English   中英

当我单击“全部”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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM