开发者

how to address list-items in the DOM

I've this markup

<ul id="body">
   <li class="item">1</li>
   <li class="item">2</li>
   <li class="item开发者_运维知识库">3</li>
   <li class="item">4</li>
</ul>

When an item is clicked, is there a way in jQuery to identify in the DOM, the previous and the next li so that I can use jQuery functions on those elements??

Say, if the person clicks on item 2, i want to hide item 1 and item 3.. similarly, if the user clicks on item 3, hide item 2 and item 4 (previous and next item in the list).


  1. Get a pointer to the previous and next elements.
  2. Select all siblings that are not the previous and next elements.
  3. Hide the previous and next siblings.
  4. Show the other elements.

This allows the code to work more than once :)

$('#body > li').click(function() {
  var prev = $(this).prev(),
      next = $(this).next(),
      siblings = $(this).siblings().not(prev).not(next);

  prev.add(next).hide();  
  siblings.show(); 

});

jsFiddle.

If you don't care if the other elements are hidden forever once clicked, simply remove the all references to the siblings variable and its relevant code.


$('#body .item').click(function() {
    $(this).prev().add($(this).next()).hide();
});

Edit:

$('#body .item').click(function() {
    $(this).siblings().show().end().prev().add($(this).next()).hide();
});

From the comment, This will show all before hiding the prev and next li elements.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜