2013-02-27 60 views
0

我公司拥有一批在页面上的div,我想折叠和展开,当用户点击“展开[+]”jQuery来展开折叠只已被点击的div

下面的代码工作的一个DIV

<h4 class="expanderHead" style="cursor:pointer;">Contact information <span class="expanderSign">Expand [+]</span></h4> 
<div id="profile-section" style="overflow:hidden;"> 
some stuff 
</div> 

<script type="text/javascript"> 
jQuery(document).ready(function(){ 
jQuery(".expanderHead").click(function(){ 
    if (jQuery(".expanderSign").text() == "Expand [+]") 
    { 
    jQuery("#profile-section").removeClass("height-min"); 
    jQuery("#profile-section").addClass("height-auto"); 
    } 
    else 
    { 
    jQuery("#profile-section").removeClass("height-auto"); 
    jQuery("#profile-section").addClass("height-min"); 
    } 

    if (jQuery(".expanderSign").text() == "Expand [+]"){ 
     jQuery(".expanderSign").text("Collapse [-]"); 
    } 
    else { 
     jQuery(".expanderSign").text("Expand [+]"); 
    } 


}); 
}); 
</script> 

如果我再有一些页面上的div这样

<h4 class="expanderHead" style="cursor:pointer;">Contact information <span class="expanderSign">Expand [+]</span></h4> 
<div id="profile-section1" style="overflow:hidden;"> 
some stuff 
</div> 

<h4 class="expanderHead" style="cursor:pointer;">Contact information <span class="expanderSign">Expand [+]</span></h4> 
<div id="profile-section2" style="overflow:hidden;"> 
some stuff 
</div> 

<h4 class="expanderHead" style="cursor:pointer;">Contact information <span class="expanderSign">Expand [+]</span></h4> 
<div id="profile-section3" style="overflow:hidden;"> 
some stuff 
</div> 

etc.... 

如何修改我的jQuery,使其适用于所有这些div的独立。即它只会最小化或最大化已被点击的div?

我已经尝试了使用(this)和parent()以及child()的一些不同组合,但是我似乎无法弄清楚它的正确性。

帮助,将不胜感激:)

回答

1

使用context with jquery selector到事件的电流源下访问元素。

语法:jQuery的(选择[,上下文])

变化

jQuery(".expanderSign").text() 

jQuery(".expanderSign", this).text() 
0

您应该使用$(this)定位在你点击的div处。

例如:

$(".expanderHead").on('click', function(){ 
    $(this).hide(); 
}); 
在这种情况下,你会点击的股利将会消失

。使用.on()而不是.click()

0

您可以通过使用肘和靶向下一格像这样把它简化:

<h4 class="expanderHead">Contact information <span class="expanderSign" style="cursor:pointer;">[+]</span></h4> 
<div class="expanderContent">some stuff</div> 

$(".expanderContent").hide(); 
$(".expanderSign").on('click', function() { 
    $(this).text($(this).text() == '[+]' ? '[-]' : '[+]'); 
    $(this).parent().next("div").toggle(); 
}); 

Example