简体   繁体   English

如何解决DOM中的列表项

[英]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?? 单击一个项目时,jQuery中是否有一种方法可以在DOM,上一个和下一个li中进行标识,以便可以在这些元素上使用jQuery函数?

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). 说,如果该人单击项目2,我想隐藏项目1和项目3。类似地,如果用户单击项目3,则隐藏项目2和项目4(列表中的上一个和下一个项目)。

  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 . 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. 如果您不关心其他元素是否在单击后永远被隐藏,只需删除对siblings变量及其相关代码的所有引用。

$('#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. 从注释中,这将显示所有隐藏prev和next li元素之前的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM