2009-11-26 173 views
8

我想通过单击标签来显示/隐藏其内容的选项来增强某些字段集。jQuery灵活隐藏/显示字段集

目前,HTML看起来像这样:

<fieldset> 
    <legend>Fieldset 1</legend> 
    <!-- Some input, p, div, whatever --> 
</fieldset> 
<fieldset> 
    <legend>Fieldset 2</legend> 
    <!-- Some input, p, div, whatever --> 
</fieldset> 

所以,对一个fieldset legend点击,任何东西,但父字段集的点击传说应该进行切换。

我尝试使用这样的:

$("fieldset *:not(legend)").hide(); 
$("fieldset legend").click(function(){ 
    $(this).nextAll().slideToggle(); 
}); 

但它不会做任何事情(甚至没有隐藏在首位的内容)。当然,我只想切换用户点击的字段集的视图,因此它必须以某种方式确定点击了哪个图例,然后隐藏相应字段集的内容。

当然,我可以给他们所有的ID,并为每个字段集编写代码,但这样看起来总是相同的,我认为必须有一种方法可以使这个功能在任何数量的字段集中都具有通用性。 ..

任何人都有一个整洁的想法?

回答

11

如果我是你,我会在包装DIV字段集的内容,并把它像:

<script type="text/javascript"> 
     $(function(){ 
      $('legend').click(function(){ 
       $(this).parent().find('.content').slideToggle("slow"); 
      }); 
     }); 
</script> 

<fieldset> 
    <legend>Fieldset 1</legend> 
    <!-- Some input, p, div, whatever --> 
    <div class="content"> 
     this<br /> 
     is<br /> 
     content<br /> 
    </div> 
</fieldset> 
<fieldset> 
    <legend>Fieldset 2</legend> 
    <!-- Some input, p, div, whatever --> 
    <div class="content"> 
     this<br /> 
     is<br /> 
     content<br /> 
    </div> 
</fieldset> 

所以,现在当你点击标签上会向上/向下滑动的内容和留下您的标签可见。

+0

是啊,这就是一个办法做到这一点,当然它会工作,但它仍然是一个黑客,并要求编辑HTML: - /仍然,谢谢。 – 2009-11-26 12:33:05

+2

这是怎么做的?...你没有指定你不想修改HTML。 – Mottie 2009-11-26 14:30:44

10
$(function(){ 
    $('legend').click(function(){ 
    $(this).siblings().slideToggle("slow"); 
    }); 
}); 

This works。这真是一个概念,只是相反。

+0

我把我的内容包裹在一个div中,并调用这个方法 - 似乎工作正常 – RozzA 2012-12-17 03:27:48

+0

效果很好。如何使负载关闭? – Dudeist 2013-09-07 14:33:37

+0

如果我正确理解你,你可以通过设置display:none来做到这一点。到你想要的任何元素“关闭”onLoad。 – creativetim 2013-09-09 23:37:55

3

扩展版本

HTML(图例包含[ - ]跨度):

<fieldset> 
    <legend>My Area <span>[-]</span></legend> 
    Content of fieldset... 
</fieldset> 

的JavaScript(需要的jQuery):

$(function(){ 
    // Set cursor to pointer and add click function 
    $("legend").css("cursor","pointer").click(function(){ 
     var legend = $(this); 
     var value = $(this).children("span").html(); 
     if(value=="[-]") 
      value="[+]"; 
     else 
      value="[-]"; 
     $(this).siblings().slideToggle("slow", function() { legend.children("span").html(value); }); 
    }); 
}); 
+0

有3个SO答案,当谷歌搜索“fieldset切换传说”,你的是最简单的+有奖+圆+/- thingy。感谢&+1。 – 2015-01-11 03:53:29