简体   繁体   中英

Toggle one div with same class

How to use Toggle when several div have the same class with jQuery? I want to show just one div on click.

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>

I can't use next() since .help_content is not a descendant of .help_target. (I want to use .help_target in fieldsets and display .help_content out of fieldsets).

采用:

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

You can do this:

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

See it in action: http://jsfiddle.net/mattball/X7p28/

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

You can achieve this by calling .parent() and then .next()

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

Code example on jsfiddle .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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