问题描述:

I have issue that I need some helps.

For example, I have HTML like:

<div class="posts">

posts 1

</div>

<div class="posts">

posts 2

</div>

<div class="posts">

posts 3

</div>

<div class="posts">

posts 4

</div>

Now, I want use Javascript/Jquery to make the number of post is visible or not.

Example: if i use js like this then 3 posts is visible, the fourth post... is invisible.

<script>

numbervisible = "3"

</script>

How can I do this with Js/jquery. Thanks.

网友答案:

You can use slice() method:

$('.posts').hide().slice(0, numbervisible).show();

And here is a working example on jsFiddle: http://jsfiddle.net/H7aTs/

网友答案:

You could also use a jQuery psuedo selector

<script>
numbervisible = '3';
$('.posts:gt(' + (numbervisible -1) +  ')').hide();
</script>

Link to jsFiddle

网友答案:

If you want to reference posts by specific ID # and not just position in list:

<div id="posts_1">
   posts 1
</div>
<div id="posts_2">
   posts 2
</div>
<div id="posts_3">
   posts 3
</div>
<div id="posts_4">
   posts 4
</div>

then:

$("#posts_" + post_no).hide();
$("#posts_" + post_no).show();
$("#posts_" + post_no).toggle();

etc.

相关阅读:
Top