2012-06-24 109 views
0

下面的代碼允許我切換LI中的div,我如何調整它以便當一個div打開時,兄弟LI內的所有其他div都關閉?切換最接近的div隱藏其他打開的div

$(document).ready(function() { 
$('.grey_button a').toggle(function() { 
    $(this).closest('li').find('.job_description').fadeIn(0); 
    $(this).toggleClass('open'); 
    //$(this).text($(this).text() == 'More Information' ? 'Hide Information' : 'More Information'); 
    return false; 
}, 
    function() { 
     $(this).closest('li').find('.job_description').fadeOut(0); 
     $(this).toggleClass('open'); 
     //$(this).text($(this).text() == 'Hide Information' ? 'More Information' : 'Hide Information'); 
    return false; 
    }); 
}); 

HTML

<ul> 
    <li> 
    <div class="grey_button"><a href="" class="arrow">More information</a></div> 
    <div class="job_description" style="display: none; "> 
     Lorem ipsum 
    </div> 
    </li> 
    <li> 
    <div class="grey_button"><a href="" class="arrow">More information</a></div> 
    <div class="job_description" style="display: none; "> 
     Lorem ipsum 
    </div> 
    </li> 
    <li> 
    <div class="grey_button"><a href="" class="arrow">More information</a></div> 
    <div class="job_description" style="display: none; "> 
     Lorem ipsum 
    </div> 
    </li> 
</ul> 

回答

1

的例如,你可以只添加一個查找所有$('.job_description').hide()

如果這將與同等級影響頁面的其他部分:

$('.grey_button a').toggle(function() { /* cache parent el */ 
    var $parent = $(this).closest('li'), 
     $list = $parent.parent(); 
    $list.find('.job_description').hide(); 
    $list.find('.open').removeClass('open') 

    $parent.find('.job_description').fadeIn(0); 

    $(this).toggleClass('open'); 
    //$(this).text($(this).text() == 'More Information' ? 'Hide Information' : 'More Information'); 
    return false; 
}, function() { 
    $(this).closest('li').find('.job_description').fadeOut(0); 
    $(this).toggleClass('open'); 
    //$(this).text($(this).text() == 'Hide Information' ? 'More Information' : 'Hide Information'); 
    return false; 
}); 
}); 
+0

這很好,除了兄弟姐妹toggleClass沒有改變。直到LI的grey_button a標籤被點擊,「open」類纔會保留。 – JV10

+0

修改了一下...新變量$ list – charlietfl

+0

非常好!現在一切正常!乾杯! – JV10

0

在這種情況下,我想你也許能減少你的代碼相當多:

$('.grey_button a').click(function(e) { 
    e.preventDefault(); 
    $('.job_description').hide(); // Reset 
    $(this).closest('.job_description').fadeToggle(); 
    $(this).toggleClass('open'); 
}); 
0

我會這樣做:

$(document).ready(function() { 
    $('.grey_button a').on('click', function(e) { 
     e.preventDefault(); 
     $('.job_description').not($(this).closest('li').find('.job_description')).hide(); 
     $(this).toggleClass('open').parent('div').next('.job_description').toggle(); 
    }); 
});​ 

FIDDLE

+0

由於某種原因,我無法在我的網站上正常工作。 – JV10