简体   繁体   中英

How do I slide down one tab and close any others that are open (JQuery/JavaScript)

Here is my code:

<script>                                                            
    $(document).ready(function () { 

        $('#t1').click(function() {  
            $('#p1').slideToggle('slow');
            $("#pm1, #pm1h").toggle(0); 
            removeContainer();
            $("#load1").load('file', showPlayer);   
        });

        $('#t2').click(function() {
            $('#p2').slideToggle('slow');
            $("#pm2, #pm2h").toggle(0);       removeContainer();
            $("#load2").load('file', showPlayer);
        });

        $('#t3').click(function() {
            $('#p3').slideToggle('slow');
            $("#pm3, #pm3h").toggle(0);       removeContainer();
            $("#load3").load('file', showPlayer);
        });

        $('#t4').click(function() {
            $('#p4').slideToggle('slow');
            $("#pm4, #pm4h").toggle(0);       removeContainer();
            $("#load4").load('file', showPlayer);
        });


    });
    </script>

Alright so what I want to do is when someone clicks on t1,t2,t3 or t4, all the other tabs that are in the slide down position will slide up (For example if t3 and t4 are down, once I click on t1 the t3 and t4 will slide up and then the t1 will slide down). This will make it so that only one tab can be open at a time.

I also need the proper toggle to correspond with the position of the tab. By default all tabs are hidden and all have a plus sign but when you click on any tab it will expand and have a negative sign. I this to stay true.

Can anyone help or need more clarification?

Your four copy-pasted blocks can be abstracted into a single one, along the lines of this:

$(function () {
  $("div.tab").click(function () {
    var idnum = this.id.replace(/\D/g, ''); // remove all "non-digits" from id

    $("#p"+idnum).slideUp('slow');
    $("div.tab").not(this).slideDown('slow'); // or the other way around

    $("#pm"+idnum+", #pm"+idnum+"h").toggle(0); 
    removeContainer();
    $("#load"+idnum).load('file', showPlayer);   
  });
}

Note that

  • $() replaces $(document).ready() .
  • not() removes an element from a set. In effect this is the "all others" you look for.
  • use a CSS class (I used .tab ) to identify and work on your elements as a set . Using IDs for that is cumbersome, as you've noticed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM