开发者

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 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜