使用.toggle jQuery展开/撤回所有内容

时间:2012-01-19 19:16:34

标签: jquery

我有一堆div,我正在使用.toggle单独扩展/收回,并希望有一个按钮可以同时扩展/收回所有。因此,如果其中一个已经展开/缩回,则在单击时将保持展开/缩回,但其余部分将展开/缩回。

以下是我为各个div使用的内容:

$('.toggle-engine').click(function() {
    $('.specs-engine').toggle(400);
$(this).text($(this).text() == '+' ? '-' : '+');
return false;
});

尝试扩展/收回所有内容,但如果其中一个已经展开,当我点击展开全部收回时:

$('.expand-all').click(function() {
            $('.specs-body').toggle(400)
    $('.specs-engine').toggle(400)
    $('.specs-curb').toggle(400)
    $('.specs-cap').toggle(400)
    $('.specs-fuel').toggle(400)
    $('.specs-brakes').toggle(400);
$(this).text($(this).text() == '+ Expand All' ? '- Retract All' : '+ Expand All');
return false;
});

这是标记:

<a class="expand-all" href="#">+ Expand All</a>
    <a class="toggle-engine" href="#">+</a>
    <div class="expand specs-engine"></div>
    <a class="toggle-body" href="#">+</a>
    <div class="expand specs-engine"></div>

2 个答案:

答案 0 :(得分:0)

您可以使用showhide代替toggle来强制它展开(展示)或收回(隐藏)元素。

另外,我建议为所有.specs-...元素设置一个公共类,例如specs,例如:

<div class="specs specs-engine"></div>
<div class="specs specs-curb"></div>
... etc

所以JS将是:

$('.specs').click(function() {$(this).toggle(400);});
$('.expand-all').click(function() {
  if ($(this).text() == '+ Expand All')
    $('.specs').show(400);
  else
    $('.specs').hide(400);
  $(this).text($(this).text() == '+ Expand All' ? '- Retract All' : '+ Expand All');
});

编辑:要使各个+ / -图片切换,请执行以下操作:

$('.specs').click(function() {$(this).toggle(400);});
$('.expand-all').click(function() {
  if ($(this).text() == '+ Expand All')
    $('.specs').show(400).find('img.plus, img.minus').hide().filter('img.plus').show();
  else
    $('.specs').hide(400).find('img.plus, img.minus').hide().filter('img.minus').show();
  $(this).text($(this).text() == '+ Expand All' ? '- Retract All' : '+ Expand All');
});

EDIT2 :如果我理解正确的话:

$('.specs').click(function() {$(this).toggle(400);});
$('.expand-all').click(function() {
  if ($(this).text() == '+ Expand All')
    $('.specs').show(400).find('.thelink').text('-');
  else
    $('.specs').hide(400).find('.thelink').text('+');
  $(this).text($(this).text() == '+ Expand All' ? '- Retract All' : '+ Expand All');
});

无论如何,你得到它,这是一个选择正确的元素和更改其文本的问题。 jQuery为单个函数调用找到的所有元素执行此操作。

答案 1 :(得分:-1)

您只需要测试是否使用函数is(':visible')

进行扩展
if( $('.your-div').is(':visible') ){
    $('.your-div').toggle();
}