2011-11-16 93 views
1

我有以下HTML:父()儿童()并切换不工作

<div class="connections"> 
    <h2>Grads that share your interests</h2> 
     <div id="connections_nav" class="collapse"> 
      <ul> 
      <li><h3><a href="">Sally Struthers </a></h3><p>Class of 2008</p></li> 
       <li><h3><a href="">Sally Struthers </a></h3><p>Class of 2008</p> 
           </li> 
      <li><h3><a href="">Sally Struthers </a></h3><p>Class of 2008</p> 
           </li> 
      </ul> 
     </div> 
</div> 

下面CSS:

.connections h2 { 
    background-image: url(images/show.gif); 
    background-position: 0px; 
    background-repeat: no-repeat; 
    color: #660a11; 
    font-size: 13px; 
    font-weight: bold; 
    margin: 0px 0px .4em; 
    padding: 0px 0px 0px 25px; } 

.connections .hide h2 { 
    background-image: url(images/hide.gif); 
    background-position: 0px; 
    background-repeat: no-repeat; } 

.connections h2.over { 
    background-image: url(images/hover-show.gif); 
    background-position: 0px; 
    background-repeat: no-repeat; } 

.connections .hide h2.over { 
    background-image: url(images/hover-hide.gif); 
    background-position: 0px; 
    background-repeat: no-repeat; } 

用下面的jQuery:

$(document).ready(function() { 

$('.connections h2').click(function() { 
    $(this).parent().children('.collapse').toggle('slow'); 
    $(this).toggleClass('hide'); 
}); 

$('.connections h2').hover( 
    function() { 
     $(this).toggleClass('over'); 
     }, 
     function() { 
     $(this).toggleClass('over'); 
}); 

});

发生什么事是整个div消失。当我取出$(this).toggleClass('hide');代码时,折叠div正确折叠(但显然,不应用显示封闭三角形图像的'hide'类)。这是为什么?

回答

1

该行$(this).toggleClass('hide')更改<h2></h2><h2 class="hide"></h2>

因此,正确的CSS选择应该是:

.connections h2.hide {} 
.connections h2.hide.over {} 

工作例如:http://jsfiddle.net/PTnXU/

您原来的选择,.connections .hide h2.over,本来是一件好事,如果你有<div><h2>之间的另一种元素,例如:

<div class="connections"> 
    <div class="hide"> 
    <h2 class="over"></h2> 
    </div> 
</div>