简体   繁体   中英

jQuery SlideToggle doesn't work on elements that are not semantically adjacent

I'm using the amazing slideToggle(); function from the jQuery API. The issue I'm encountering is that I thought I could target the next .slide_toggle_container by using the following jQuery code:

$(document).ready(function() {
    //Hide (Collapse) the toggle containers on load
    $(".toggle_container").hide(); 

    //Switch the "Open" and "Close" state per click then slide up/down (depending on open/close state)
    $(".trigger").click(function(){
        $(this).toggleClass("active").next(".toggle_container").slideToggle("slow");
        return false; //Prevent the browser jump to the link anchor
    });

}); // End of document.ready    

The problem is that the above code works great with the following HTML

            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam eget venenatis turpis. Fusce et ante diam, venenatis vestibulum tortor. Nam ultrices accumsan velit sit amet sagittis.</p>

            <a class="trigger toggle" href="#">Read More</a>

            <div class="toggle_container">Sliding Content</div>

But for styling purposes, I need to use the following HTML, which causes the .trigger and slideToggle to not work.

            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam eget venenatis turpis. Fusce et ante diam, venenatis vestibulum tortor. Nam ultrices accumsan velit sit amet sagittis.<a class="trigger toggle" href="#">Read More</a></p>

            <div class="toggle_container">Sliding Content</div>

My understanding from some research is that the HTML above (2nd) does not work because the .trigger is contained within <p> and the slide_toggle_container is not recognized as the .next() element in the DOM. Any help? How can I make this work with the second HTML scenario above?

Use parent() method to access the parent of the anchor and then call next to access the div.

Change:

 $(this).toggleClass("active").next(".toggle_container").slideToggle("slow");  

to

 $(this).toggleClass("active").parent().next(".toggle_container").slideToggle("slow"); 

Try this

$(document).ready(function() {
    //Hide (Collapse) the toggle containers on load
    $(".toggle_container").hide(); 

    //Switch the "Open" and "Close" state per click then slide up/down (depending on open/close state)
    $(".trigger").click(function(){
        $(this).toggleClass("active").closest("p").next(".toggle_container").slideToggle("slow");
        return false; //Prevent the browser jump to the link anchor
    });

}); // End of document.ready 

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