8

I want to enhance some fieldsets with the option to show / hide their contents upon clicking their label.

Currently, the HTML looks like this:

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

So, on click of one fieldset legend, anything but the clicked legend of the parent fieldset should be toggled.

I tried using this:

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

But it doesn't do anything (not even hide the contents in the first place). Of course I want to only toggle the view on the very fieldset the user has clicked, so it has to somehow determine what legend was clicked and then hide the contents of the corresponding fieldsets.

Sure, I could give them all IDs and write the code for every fieldset, but thats rather redundant seeing it would always be the same I think there has to be a way to make this functionality universal for any amount of fieldsets...

Anyone has a neat idea?

4

3 に答える 3

12

私があなただったら、fieldset のコンテンツを 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>

したがって、ラベルをクリックすると、コンテンツが上下にスライドし、ラベルが表示されたままになります。

于 2009-11-26T10:53:17.807 に答える
10
$(function(){
  $('legend').click(function(){
   $(this).siblings().slideToggle("slow");
  });
});

これは機能します。それは実際には同じ概念であり、逆です。

于 2010-01-14T06:19:51.987 に答える
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); } );
    });
});
于 2013-10-08T11:23:01.133 に答える