问题
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).
回答1:
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/
回答2:
Use:
$(this).closest("div").next(".help_content").toggle();
回答3:
$(".help_target").click(function()
{
$(this).parent().next().toggle(); // I also try with $(".help_content").show();
});
回答4:
You can achieve this by calling .parent() and then .next()
$(".help_target").click(function()
{
$(this).parent().next('.help_content').toggle();
});
Code example on jsfiddle.
回答5:
Why not give the div a unique Id and then call the toggle function
$("#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;
});
来源:https://stackoverflow.com/questions/5551888/toggle-one-div-with-same-class