Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - How to toggle only the *next* & hide other class

i have some problem in collapsable jquery.

My HTML elements are like this

    <div id="first" class="collapse-container">

        <h1 class="collapse">
        <span class="arrow-r"></span>First Heading</h1>
        <div class="accordion-active">
            <p>First Section</p>
            <p>First Section</p><p>First Section</p>
        </div>
        <h1 class="collapse"><span class="arrow-r"></span>Second Heading</h1>
        <div class="accordion-active">
            <p>Second Section</p>
            <p>Second Section</p>
        </div>
        <h1 class="collapse"><span class="arrow-r"></span>Third Heading</h1>
        <div class="accordion-active">
            <p>Third Section</p>
            <p>Second Section</p>
        </div>
    </div>

I am using this jquery for toggle class

    $(document).ready(function () {
        $(".collapse").click(function () {
            $(this).toggleClass("active");
        });
    });

    jQuery(document).ready(function() {
      jQuery(".accordion-active").hide();
      //toggle the componenet with class msg_body
      jQuery(".collapse").click(function()
      {
        jQuery(this).next(".accordion-active").slideToggle(0);

      });
    });

Now my problem, when i clicks on first h1 tag it only shows its elements.thats fine. But now when i click on 2nd h1 tag it shows its elements, BUT FIRST H1 TAG IS STILL OPEN.

How can i set all others hide, while one (next class) is active?

Thanks

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Try this.

$(".accordion-active").hide();

//toggle the componenet with class msg_body
$(".collapse").click(function(){

  var $this = $(this); //  Cacheing $(this)

  $('.accordion-active').slideUp();

  if( !$this.next(".accordion-active").is('.open') ){
    //$('h1').removeClass('active');
    $('.accordion-active').removeClass('open');
    $this.addClass("active").siblings("h1").removeClass("active");
    $this.next(".accordion-active").addClass('open').slideDown();
  } else {
    $("h1").removeClass("active");
    $this.next(".accordion-active").removeClass('open').slideUp(); 
  }

});

Fiddle Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.7k users

...