开发者

How to works with indexes in jQuery?

We have html code like:

<div class="blocks">
    <div class="block"></div>
    <div class="block"></div>
    <div class="block"></div>
    <div class="block"></div>
    <div class="block"></div>
    <div class="block"></div>
    <div class="block"></div>
    <div class="block"></div>
    <div class="block"></div>
    <div class="block"></div>
</div>

How do 开发者_运维问答I get:

1) first five elements?

2) number of visible blocks (they can be invisible).

3) number of all elements?

4) number of invisible elements?

5) make visible element(n)?

6) make invisible elements from n to n?

n is an index number.

That's all corresponding only to .block divs.


1) first five elements?

$('.block:lt("5")'); // zero-based indexing.

2) number of visible blocks (they can be invisible).

$('.block:visible').length; // gets all visible '.block' elements.

$('.block:visible:lt("5")'); // the first five elements
$('.block:visible:gt("2")'); // all elements after the third (zero-based indexing)

3) number of all elements?

$('.block').length;

4) number of invisible elements?

$('.block').not(':visible');
$('.block:hidden'); // thanks @strager

5) make visible element(n)?

$('.block').eq(n).show();

6) make invisible elements from n to n?

$('.block').each(
    function(i){
    var lowBound = 2, highBound = 10;
        if (i > lowBound && i < highBound) {
            $(this).hide();
        }
     });

$('.block').slice(low, high).hide(); // use this approach, it's much better! Thanks, again, @strager

References:

  • lt().
  • gt().
  • not().
  • eq().
  • show().
  • each().
  • index().


The JQuery site has good documentation with examples on using Selectors.

  • Selectors Documentation

This site is useful giving examples and you can try out the selectors as a learning exercise.

  • Selectors Examples
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜