简体   繁体   中英

Toggle the nearest content when click on anchor using jQuery

I have a content structure like this:

<a href="#" class="toggle_button">Click me.</a>
<p class="hidden_content">This content is toggleable.</p>

<a href="#" class="toggle_button">Click me.</a>
<p class="hidden_content">This is a different section.</p>

<a href="#" class="toggle_button">Click me.</a>
<p class="hidden_content">This section is also different.</p>

I have already discovered how to make this work with one section, but how can I make it so that when I click on a toggle_button it opens only the nearest hidden_content class.

$('a.toggle_button').click(function() {
    $(this).next('p.hidden_content').toggle();
}

http://api.jquery.com/next/

Simply try

$("a").click( function(){
   $(this).next('p').toggle();   
});

Working Demo

It's easy with JavaScript but you could also stay with plain CSS with the :target selector --

<a href="#hiddenContent1" class="toggle_button">Click me.</a>
<p id="hiddenContent1" class="hidden_content">This content is toggleable.</p>

<style>
 .hidden_content{
    display:none;
 }
 .hidden_content:target{
    display:block;
 }
</style>

Here's a Fiddle

This will toggle the following div, and stop the page returning to the top:

$('a.toggle_button').click(function(e) {
    e.preventDefault();
    $(this).next('p.hidden_content').toggle();
}

Use the jQuery .next() selector

$(".toggle_button").on("click", function () {
    $(this).next(".hidden_content").toggle();
});

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