parent()。children()和toggle无法正常工作

时间:2011-11-16 20:06:09

标签: jquery toggle parent children toggleclass

我有以下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 个答案:

答案 0 :(得分: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>