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
1.8k views
in Technique[技术] by (71.8m points)

javascript - How to open and collapse the same JQuery accordion with click on it only

Trying to get the accordion open and collapse only when it's being clicked. I am able to open/collapse it but it is getting closed also when another accordion is clicked.

It should open or close on its own - independently from other accordions.

This is what I have tried.

JS:

$(document).on("click", ".accordion-toggle", function () {
        if ($(this).attr('class').indexOf('open') == -1)
   $(this).toggleClass("open").next().slideToggle('fast');
        //Hide the other panels
        $(".accordion-toggle").not($(this)).removeClass("open");
        $(".accordion-content").not($(this).next()).slideUp('fast');
    });

Fiddle: Demo

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

I have created a new fiddle with some css...

HTML

<div class="accordion-container">
    <a href="#" class="accordion-toggle">Heading 1</a>
    <div class="accordion-content">
        Content 1
    </div>
</div>
<div class="accordion-container">
    <a href="#" class="accordion-toggle">Heading 2</a>
    <div class="accordion-content">
        Content 2
    </div>
</div>
<div class="accordion-container">
    <a href="#" class="accordion-toggle">Heading 3</a>
    <div class="accordion-content">
        Content 3
    </div>
</div>

JS

$(document).ready(function () {
    $('.accordion-toggle').on('click', function(event){
        event.preventDefault();
        // create accordion variables
        var accordion = $(this);
        var accordionContent = accordion.next('.accordion-content');

        // toggle accordion link open class
        accordion.toggleClass("open");
        // toggle accordion content
        accordionContent.slideToggle(250);

    });
});

please check this fiddle


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

...