开发者

How do I set elements without a specific class to hidden using JQuery?

开发者 https://www.devze.com 2023-04-05 03:34 出处:网络
I have several divs on a page all with the class \"article.\" I used $(\".article:first\").addClass(\"current\");

I have several divs on a page all with the class "article." I used

$(".article:first").addClass("current");

to add the clas开发者_运维问答s "current" to the first div with class "article." I want all other class="article" divs to be hidden until a button is clicked.

When the page loads, the first class="article" div should be visible. When a button is clicked, the 2nd div should appear, and so on.

Edit: Does it matter that the class="article" divs appear in two differently-classed divs?

<div class="roots">
   <div class="article">
   </div>
</div>
<div class="words">
   <div class="article">
   </div>
</div>

Would I have to address them differently in JQuery?


$(".article").not(":first").hide()

or

$(".article").not(".current").hide()


You can set the initial state of only the first one showing with this jQuery:

$(document).ready(function() {
    $(".article").hide();  // hide them all
    $(".article:first").show().addClass("current");  // show first one and add class
});

Though, I wouldn't personally use JS for the initial state myself because they elements may show briefly before the JS runs and it might not look so clean. It might be better to have .article be hidden by default with CSS:

.article {display: none;}

And, then you run this initial javascript to show the first one and add your current class:

$(document).ready(function() {
    $(".article:first").show().addClass("current");  // show first one and add class+
});

Then, upon a button press, to show the next one that's hidden you can execute this:

$("#showButton").click(function() {
    $(".article:hidden:first").show();
});

You can see a working example of this here: http://jsfiddle.net/jfriend00/RPPYz/.


To hide all but the first post, try this:

$(".article").not(":first").hide();

To hide all posts without the class current, use this:

$(".article").not(".current").hide();

To show each article one by one when a button is clicked, use this selector:

$(".article.current:hidden").first().show();

More about the :hidden selector can be found here.

0

精彩评论

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