Using JQuery how to show and hide different div's onClick event

前端 未结 12 637
死守一世寂寞
死守一世寂寞 2021-01-03 03:34

I would like to show a div based on the Onclick event of an link.

First Click - Show div1
Second Click - Hide remaining div\'s and Show div2
Third Click

相关标签:
12条回答
  • 2021-01-03 03:52
    var c = 1;
    $("#toggle_value").click(function()
    {
       $("#div" + c).hide("fast");        
       $("#div" + ++c).show("fast");
       if (c > 3) c=1;       
    });
    
    0 讨论(0)
  • 2021-01-03 03:53

    You should add a counter in the function.

    $(document).ready(function() {
        var count = 0;
    
        $("#toggle_value").click(function(){
            if (count == 0) {
                $("#div1").show("fast");
                $('#div2').hide();
                count++;
            }
            else if (count == 1) {
                $("#div2").show("fast");
                ...
                count++;
            }
            else if (count == 2) {
                $("#div3").show("fast");
                ....
                count++;
            }
            else {
                 $('div').hide();
                 count=0;
            }
        });
    });
    
    0 讨论(0)
  • 2021-01-03 03:55

    I prefer to use "filter" method and make a little easier work with counter:

    (function () {
        var divCounter = 0, divs;
    
        $(function () {
            divs = $('#div1, #div2, #div3');
            $('#toggle_value').click(function (e) {
                divs.hide() // hide other divs
                    .filter(function (index) { return index == divCounter % 3; }) // select appropriate div
                    .show('fast'); // and show it
    
                divCounter++;
            });
        });
    
    })();
    
    0 讨论(0)
  • 2021-01-03 03:57

    I would probably do something like: (The following assumes all your <div>s are in a container with id "container")

    $(document).ready(function() {
      var $allDivs = $("#container > div");
      var counter = 0;
    
      $("#container > div").click(function(){
        counter = counter < $allDivs.length - 1 ? counter + 1 : 0;
        $allDivs.not(":eq("+counter +")").hide("fast");
        $allDivs.eq(counter).show("fast");
      });
    });
    
    0 讨论(0)
  • 2021-01-03 04:01

    A simple way would be to introduce a variable that tracked clicks, so something like this:

    var tracker = 0;    
    $(document).ready(function() {
        $("#toggle_value").click(function(){
           if(tracker == 0)
           {
              $("#div1").show("fast");
           }else if(tracker ==1)
    
           etc etc
    
           tracker ++;
    
        });
    });
    
    0 讨论(0)
  • 2021-01-03 04:01

    The .toggle function in jQuery takes any number of argument functions, so the problem is already solved. See the docs under Events.

    0 讨论(0)
提交回复
热议问题