【问题标题】:Toggle one div with same class切换一个具有相同类的 div
【发布时间】:2011-04-05 20:51:41
【问题描述】:

多个div与jQuery同一个类的情况下如何使用Toggle?我只想在点击时显示一个 div。

JavaScript

$(".help_content").hide();
$(".help_target").click(function()
{
    $('.help_content').toggle(); // I also tried with $(".help_content").show();
});

HTML

<div id="foo">
    <p class="help_target">
            <a href="#">Click</a>
    </p>
</div>
<p class="help_content">Asia</p>

<div id="some">
    <p class="help_target">
        <a href="#">Click</a>
    </p>
</div>
<p class="help_content">Africa</p>

我不能使用 next(),因为 .help_content 不是 .help_target 的后代。 (我想在字段集中使用 .help_target 并在字段集中显示 .help_content)。

【问题讨论】:

    标签: jquery toggle


    【解决方案1】:

    你可以这样做:

    $(".help_content").hide();
    $(".help_target").click(function()
    {
        $(this).parent().next('.help_content').toggle();
    });
    

    查看实际操作:http://jsfiddle.net/mattball/X7p28/

    【讨论】:

    • 非常感谢,马特。我忘记了父母!文森特
    【解决方案2】:

    用途:

    $(this).closest("div").next(".help_content").toggle();
    

    【讨论】:

      【解决方案3】:
      $(".help_target").click(function()
      {
          $(this).parent().next().toggle(); // I also try with $(".help_content").show();
      });
      

      【讨论】:

        【解决方案4】:

        您可以通过调用.parent() 然后.next() 来实现此目的

        $(".help_target").click(function()
        {
            $(this).parent().next('.help_content').toggle();
        });
        

        jsfiddle 上的代码示例。

        【讨论】:

        • 我先看到马特的回答,抱歉。
        【解决方案5】:

        为什么不给div一个唯一的id,然后调用toggle函数

        $("#help_content_DIV_ID").toggle();
        

        【讨论】:

        • 是的,你是对的。我以为。但是,我更愿意找到一个更通用的解决方案,以便稍后在另一个更复杂的项目中实现它。
        【解决方案6】:
        $('.help_target>a').click(function() {
           $('.help_content').hide();
           $(this).closest('.help_target').parent().next('.help_content').eq(0).show();
           return false;
        });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-01-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多