开发者

jQuery accordion, clicking an already opened accordion item just toggles it

开发者 https://www.devze.com 2022-12-08 03:18 出处:网络
I have a semi-working example that you can look at. This appears to work as most would desire, though it shares a bug I am seeing in many other accordions, which is if you click on the an already ope

I have a semi-working example that you can look at.

This appears to work as most would desire, though it shares a bug I am seeing in many other accordions, which is if you click on the an already opened header link, it will be closed, and then opened again.

Any elegant solutions?

Here is the jQuery

 <script language="javascript">
      $(document).ready(function() {

        // Simple Accordion Style Menu Function
        $('h2.question').click(function() {
            $('div.answer').slideUp('normal');  
            $(this).next().slideDown('normal');
        });

        // Closes All Divs on Page Load
        $("div.answer").hide();

        // Opens the first div
        var Current = $('.question:first');
           Current.next().show();

      });
 </script>

And here is the basic markup I am looking to use:

 <div class="accordion">
      <h2 class="question"><a href="#">Header 1</a></h2>
      <div class="answer">
           <p>some body content 1</p>
           <p>some body content 2</p>
           <p>some body content 3</p>
      </div>

      <h2 class="question"><a href="#">Header 2</a></h2>
      <div class="answer">
           <p>some body content a</p>
           <p>some body content b</p>
           <p>some body content c</p>
      </div>

      <h2 class="question"><a href="#">Header 3</a>开发者_如何学Python</h2>
      <div class="answer">
           <p>some body content x</p>
           <p>some body content y</p>
           <p>some body content z</p>
      </div>
 </div>


You could try adding a class on the h2 to note its active then check for that on each h2 click? If it has the active class on it then do nothing as it is already open. Also on page load it gives the first h2.question a class of active.

<script language="javascript">
      $(function() {
            // Simple Accordian Style Menu Function
            $('h2.question').click(function() {
              if(!$(this).hasClass('active')) {
                $('div.answer:visible').slideUp('normal').prev('h2.question').removeClass('active');
                $(this).addClass('active').next().slideDown('normal');
              }
            });

            // Closes All Divs on Page Load
            $("div.answer").hide();

            // Opens the first div
            var Current = $('h2.question:first');
               Current.addClass('active').next().show();

          });
     </script>
0

精彩评论

暂无评论...
验证码 换一张
取 消