繁体   English   中英

jQuery SlideToggle 不适用于语义上不相邻的元素

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

我正在使用惊人的slideToggle(); function 来自 jQuery API。 我遇到的问题是我认为我可以使用以下 jQuery 代码来定位下一个.slide_toggle_container

$(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    

问题是上面的代码适用于以下 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>

但出于造型目的,我需要使用以下 HTML,这会导致.triggerslideToggle不起作用。

            <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>

我从一些研究中了解到,上面的 HTML (第 2 次)不起作用,因为.trigger包含在<p>中,并且slide_toggle_container未被识别为 DOM 中的.next()元素。 有什么帮助吗? 如何在上面的第二个 HTML 场景中使用它?

使用parent()方法访问锚的父级,然后调用 next 访问 div。

改变:

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

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

尝试这个

$(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 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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