Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

html - jquery - Collapsing / Expanding divs?

Trying to create collapsible / expandable divs using jQuery, but it's not working for me at all... Each h3 should expand/collapse the div beneath it, and I'm not sure why this isn't working... Granted, is a heavily nested div, but I thought that the script below would find the uforms class regardless of how much other markup is on the page when it loads and then do what it's supposed to do...

Here's the jquery:

$(document).ready(function () {
        $('div.uforms:eq(1)> div:gt(-1)').hide();
        $('div.uforms:eq(1)> h3').click(function() {
                $(this).next('div:hidden').slideDown('fast').siblings('div:visible').slideUp('fast');
        });
});

And, the markup (minus all the stuff that's actually inside the <div></div>, because it's a lot of form stuff...)

<div class="uforms">
  <h3>Heading</h3>
  <div></div>

  <h3>Heading</h3>
  <div></div>

  <h3>Heading</h3>
  <div></div>
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You're selectors are just wrong. You don't need eq or gt

$(document).ready(function () {
    $('.accordion > div').hide();
    $('.accordion> h3').click(function() {
        $(this).next('div:hidden').slideDown('fast').siblings('div:visible').slideUp('fast');
    });
});

I would change the class identified to something more general so you can reuse this in other places.

<div class="accordion">
    <h3>Heading</h3>
    <div>cactuspants! <div>I am an inner div</div></div>

    <h3>Heading</h3>
    <div>Hats</div>

    <h3>Heading</h3>
    <div>Hi!</div>
</div>

Also, others have suggested that you just use jQueryUI, which is completely valid, unless you're not already using it or intend to use it for additional features. A s3 line function beats including an addition 32K library (the size of the minimally necessary components in a customized build).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...