开发者

jQuery - show/hide DIVs is they have a certain class

开发者 https://www.devze.com 2023-02-12 08:10 出处:网络
Here is my code : <div id=\"principal\" class=\"classxx\"> <div class=\"class001 cat2 blabla\">

Here is my code :

  <div id="principal" class="classxx">
    <div class="class001 cat2 blabla">
      <div class="class002">
        <div class="class003"></div>
        <div class="class004"></div>
        <div class="class005"></div>
      </div>
    </div>
    <div class="class001 cat3 blabla">
      <div class="class002">
        <div class="class003"></div>
        <div class="class004"></div>
        <div class="class005"></div>
      </div>
    </div>
    <div class="class001 cat1 blabla">
      <div class="class002">
        <div class="class003"></div>
        <div class="class004"></div>
        <div class="class005">&开发者_如何学JAVAlt;/div>
      </div>
    </div>
  </div>

I need a function like :

function showOnlyCat(className){}

If I call showOnlyCat('cat3') I want to see only all the DIVs that have the 'cat3' class (each DIV having multiple classes) and its children of course The function has to target only first children of DIV#principal

And I also need a showAllCat() that shows all the children DIVs of DIV#principal

Thank you VERY MUCH for your help


function showOnlyCat(className){
 $("#principal").children().hide().filter("."+className).show();
}

function showAllCat(){
 $("#principal").children().show();
}

Edit: Fixed the bugs. Tested. It works.

Edit2: Following good suggestion from @gnarf


hello with jQuery you can do that:

function showAllCat() {
    $('#principal div').each(function() {
        $(this).css('display', 'block');
    })
}

function showOnlyCat(className) {
    $('#principal div:not(.' + className + ')').each(function() {
        $(this).css('display', 'none');
    })

    $('#principal div.' + className).each(function() {
        $(this).css('display', 'block');
    })
}

//other way:
function showOnlyCat1(className) {
    //hide all
    $('#principal div').each(function() {
        $(this).css('display', 'none');
    })
    //showing only class parameter
    $('#principal div.' + className).each(function() {
        $(this).css('display', 'block');
    })
}
0

精彩评论

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