2011-07-13 12 views
0

我正在使用jQuery API中令人惊叹的slideToggle();函数。我现在遇到的问题是,我想我可以通过使用下面的jQuery代码锁定下.slide_toggle_containerjQuery SlideToggle无法在语义上不相邻的元素上工作

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

我从一些研究的理解是,因为.trigger被包含在<p>slide_toggle_container没有被识别为DOM中.next()元素的HTML上述(2日)不起作用。任何帮助?我如何使用上面的第二个HTML场景做这项工作?

回答

2

使用parent()方法来访问锚的父母,然后调用next,进入格。

变化:

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

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

试试这个

$(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 
相关问题