切换一个具有相同类的div

时间:2011-04-05 12:35:22

标签: jquery toggle

当几个div与jQuery具有相同的类时,如何使用切换?我想在点击时只显示一个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)。

6 个答案:

答案 0 :(得分:3)

使用:

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

答案 1 :(得分:3)

你可以这样做:

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

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

答案 2 :(得分:0)

$(".help_target").click(function()
{
    $(this).parent().next().toggle(); // I also try with $(".help_content").show();
});

答案 3 :(得分:0)

您可以致电.parent()然后.next()

来实现这一目标
$(".help_target").click(function()
{
    $(this).parent().next('.help_content').toggle();
});

jsfiddle上的代码示例。

答案 4 :(得分:0)

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

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

答案 5 :(得分:0)

$('.help_target>a').click(function() {
   $('.help_content').hide();
   $(this).closest('.help_target').parent().next('.help_content').eq(0).show();
   return false;
});