【问题标题】:I want to toggle .textDecoration class when I am clicking on "ALL" h1 elements. Can you Help me with this Code? [duplicate]当我单击“所有”h1 元素时,我想切换 .textDecoration 类。你能帮我看看这个守则吗? [复制]
【发布时间】:2022-01-07 14:13:33
【问题描述】:

我只能访问 h1 中的第一个元素。我还可以创建一个按钮并单击循环遍历 h1 元素并打开或关闭 .textDecoration 类。但我的目标是一步一步单击我想要的元素并打开或关闭 .textDecoration 类。

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>

【问题讨论】:

    标签: javascript html css toggle getelementsbytagname


    【解决方案1】:

    我建议你委托

    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>

    【讨论】:

    • 感谢您的帮助。这对我来说更简单......
    【解决方案2】:

    在我看来,您的问题表述得非常糟糕,您在寻找吗?

    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>

    【讨论】:

    • 有趣但难以阅读
    • 是的,我想要那样,谢谢你的帮助,现在下面的答案对我来说更简单。我知道这也是一个简单的解决方案,但我只是初学者,第二个解决方案在我看来更简单
    • Hn.addEventListener("click", _=&gt; 推荐。我测试了它也有效
    猜你喜欢
    • 2021-10-15
    • 2017-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 2021-01-28
    • 2011-12-08
    相关资源
    最近更新 更多