【问题标题】:Click function on class点击类功能
【发布时间】:2016-08-18 08:46:33
【问题描述】:

如果我想在 h3 show p 上点击,我该如何改进我的脚本 - 但我有更多这些元素,它们在点击时全部打开。有必要给所有h3 id吗?

$('.question h3').click(function(){
$('.question p').toggle();
});

【问题讨论】:

    标签: jquery html class onclick toggle


    【解决方案1】:

    你可以这样试试吗:

    https://jsfiddle.net/ay6xocLx/1/

     $('.question h3').click(function(){
        $(this).next('p').toggle();
     });
    

    通过$.next(),我们正在定位下一个 DOM 元素。

    【讨论】:

    • @AnnieTheCross 如果此答案回答了您的问题,请将其标记为答案并创建一个包含任何其他问题的问题。不要更改原始问题。
    【解决方案2】:

    p 元素是h3 元素的直接下一个兄弟元素。您可以将.next() 与单击的元素 jquery 对象一起定位到相关的p 元素:

    $('.question h3').click(function(){
      $(this).next().toggle();
    });
    

    $('.question h3').click(function(){
      $(this).next().toggle();
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="question">
    <h3>One</h3>
    <p>p - one</p>
    <h3>Two</h3>
    <p>p - two</p>
    <h3>Three</h3>
    <p>p - three</p>
    </div>

    【讨论】:

      【解决方案3】:

      由于.next() 是出了名的脆弱(只需在 SO 中搜索“为什么 .next 不起作用”之类的问题),您可以将 h3/p 包装在另一个 div 中,从而为您提供更好的 html 布局灵活性。

      <div class="question">
          <div class='answer'>
              <h3>One</h3>
              <p>p - one</p>
          </div>
          <div class='answer'>
              <h3>Two</h3>
              <p>p - two</p>
          </div>
          <div class='answer'>
              <h3>Three</h3>
              <hr />
              <p>p - three</p>
          </div>
      </div>
      

      然后您可以上到包装器 div 并返回到 p

      你会在第三季度看到,我添加了&lt;hr&gt;,然后任何使用.next().next("p") 的解决方案都将失败。

      $('.question h3').click(function(){
          $(this).closest(".answer").find("p").toggle();
      });
      

      .next() 的另一种选择。是.nextAll().first(),即:

      $('.question h3').click(function(){
          $(this).nextAll("p").first().toggle();
      });
      

      这还允许 html 具有更大的灵活性,并且可以与上面添加的 &lt;hr/&gt; 一起使用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-02-27
        • 2011-01-28
        • 1970-01-01
        • 1970-01-01
        • 2013-04-30
        • 2021-11-23
        • 1970-01-01
        相关资源
        最近更新 更多