One function to toggle multiple hidden elements?

后端 未结 3 576
粉色の甜心
粉色の甜心 2021-01-26 12:55

This is just a snippet but I will have many different links on a page. Each link will have a different hidden element associated with it. I\'m trying to avoid writing 100 diff

相关标签:
3条回答
  • 2021-01-26 13:19

    You may use given below toggle function to toggle multiple elements by giving array of element id as input.

    For example:

         toggleElements(["elem1","elem2"],["elem3"]);
         OR
         toggleElements(arr1,arr2);
    
    function showElements(showEls){
           for(var i=0; i<showEls.length; i++){
               if($("#"+showEls[i]).is(':hidden')) $("#"+showEls[i]).show();
           }
    }
    function hideElements(hideEls){
           for(var i=0; i<hideEls.length; i++){
              if($("#"+hideEls[i]).is(':visible')) $("#"+hideEls[i]).hide();
           }
    }
    
    function toggleElements(arr1,arr2){
            if(true){
                if($("#"+arr1[0]).is(":hidden")){
                     showElements(arr1);
                     hideElements(arr2);
                }else{
                     showElements(arr2);
                     hideElements(arr1);
                }
            }
    }
    
    0 讨论(0)
  • 2021-01-26 13:24

    You would ideally need a way to link the links to the right div. You can do this using the data attributes like this.

    HTML:

    <a class="county" data-divId="stats1" href="#">one</a><br/>
    <a class="county" data-divId="stats2" href="#">two</a>
    <div id="stats1" class="countystats">stats one</div>
    <div id="stats2" class="countystats">stats two</div>
    

    JS:

    $('.county').click(function() {
        $('#' + $(this).data('divId')).slideToggle();
    });
    

    Example - http://jsfiddle.net/infernalbadger/6wDf9/

    This should be quite easy to do if you are dynamically generating these links.

    0 讨论(0)
  • 2021-01-26 13:39

    You could use:

    $('.county').click(
        function(){
            var thisIs = $(this).index();
            $('.countystats').eq(thisIs).slideToggle(300);
        });
    

    JS Fiddle demo.

    Note that I removed the br from the html to get the index() accurately. If you need a elements to be one-per-line, use:

    a {
        display: block;
    }
    

    References:

    • eq().
    • index().
    • slideToggle().
    0 讨论(0)
提交回复
热议问题