【问题标题】:Display only closest list elements仅显示最近的列表元素
【发布时间】:2012-12-23 06:59:05
【问题描述】:

这里是an example of what I have already

主要功能可以工作,但现在我需要缩小控制器列表,以便它更适合屏幕,因为它是固定位置的。

所以,我认为它应该显示来自活动项的下三个列表项和前两个列表项。

这样的事情会起作用,但我认为应该有更短更方便的方式:

//Display closest items
$('#historyController li.active').prevAll('li:not(.first)').hide().slice(0,2).show();
$('#historyController li.active').nextAll('li:not(.last)').hide().slice(0,3).show();

任何重构当前代码以获得更好性能的技巧也会有所帮助。

【问题讨论】:

  • Something like this would work, but I think there should be shorter and more convinient wayany tips for re-factoring current code for better performance would be helpful as well 如果没有任何问题并且您的代码可以正常工作,但您只是在寻找替代或更好的方法,那么这个问题可能会在 Stackexchange - Code Review 上更好
  • 不确定我是否完全理解,但“最接近”的方法是否对您有帮助:api.jquery.com/closest

标签: javascript jquery navigation html-lists


【解决方案1】:
<ul>
   <li>list item 1</li>
   <li>list item 2</li>
   <li class="third-item">list item 3</li>
   <li>list item 4</li>
   <li>list item 5</li>
</ul>

$('li.third-item').next().css('background-color', 'red');

文档链接next()

这是您可以用于tree-traversal的所有项目

【讨论】:

    【解决方案2】:

    使用下面的 jQuery 函数。

    <ul id="one" class="level-1">
    <li class="item-i">I</li>
    <li id="ii" class="item-ii">II
    <ul class="level-2">
    <li class="item-a">A</li>
    <li class="item-b">B
    <ul class="level-3">
    <li class="item-1">1</li>
    <li class="item-2">2</li>
    <li class="item-3">3</li>
    </ul>
    </li>
    <li class="item-c">C</li>
    </ul>
    </li>
    <li class="item-iii">III</li>
    </ul>
    

    jquery 函数是..

    $('li.item-a').closest('ul').css('background-color', 'red');
    

    【讨论】:

    • 这似乎不是 Algeron 想要的。请在发布答案之前仔细阅读问题。
    【解决方案3】:

    您可以尝试使用.end(),以节省遍历:

    $('#historyController li.active').prevAll('li:not(.first)').hide().slice(0,2).show().end().end().nextAll('li:not(.last)').hide().slice(0,3).show();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多