how to show divs with specific class

问题内容:

I need to show only specific divs in aone page. I want to put all the divs in the page and that I will have a button that change which divs the browser shows every time.
this is my code:

<div class="all red">content..</div>
<div class="all blue">content..</div>
<div class="all red">content..</div>
<div class="all green">content..</div>
<div class="all blue">content..</div>

All stands for an option to show all the divs and every div has its own seperate class that I want choose. halp??

问题评论:

    
please do accept/upvote answer if it woks for you….

答案:

答案1:

you have to do like this , you have to use show() -for showing div, and hide()-for hiding div method of jquery

$("div.red").show();--this show red
$("div.blue").show();--this show blue
$("div.green").show();--this show green

答案评论:

    
And how do I connect it to a button?
– boltan
1 hour ago
    
@boltan have you done any research yourself so far? There are things like eventhandlers that let you connect a button to an event (click) and then to an action (hiding / showing your divs)

答案2:

You can do something similar to this:

$('button').click((e) => {

$('.all').hide();
$('.' + e.target.id).show();

});
.all {
  width: 100px;
  height: 40px;
}

.red {
  background-color: red;
}

.blue {
  background-color: blue;
}

.green {
  background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="all red">content..</div>
<div class="all blue">content..</div>
<div class="all red">content..</div>
<div class="all green">content..</div>
<div class="all blue">content..</div>

<button id="all">all</button>
<button id="red">red</button>
<button id="blue">blue</button>
<button id="green">green</button>

答案评论:

答案3:

Since you are using jQuery, it gets lot easier. Simply set the initial display of all the classes you want hidden to “none”

.red{
     display:none; 
}

And then set the display to block in your event handler function.

$(".red").css("display","block");

Hopefully that solves it.

答案评论:

原文地址:

https://stackoverflow.com/questions/47754859/how-to-show-divs-with-specific-class

添加评论

友情链接:蝴蝶教程