【问题标题】:parent().children() and toggle not workingparent().children() 和切换不起作用
【发布时间】:2011-11-16 20:06:08
【问题描述】:

我有以下 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 正确折叠(但显然没有应用显示闭合三角形图像的“隐藏”类)。这是为什么?

【问题讨论】:

    标签: jquery toggle parent children toggleclass


    【解决方案1】:

    $(this).toggleClass('hide') 行将 &lt;h2&gt;&lt;/h2&gt; 更改为 &lt;h2 class="hide"&gt;&lt;/h2&gt;

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

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

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

    如果您在 &lt;div&gt;&lt;h2&gt; 之间有另一个元素,您的原始选择器 .connections .hide h2.over 会很好,例如:

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

    【讨论】:

      猜你喜欢
      • 2013-10-25
      • 1970-01-01
      • 2017-11-29
      • 1970-01-01
      • 1970-01-01
      • 2014-07-28
      • 1970-01-01
      • 2014-09-09
      • 1970-01-01
      相关资源
      最近更新 更多