简体   繁体   English

通过元素组合在一起的jQuery对象循环

[英]Cycling through a jQuery object with elements grouped together

I have a set of list items that contain nested lists, sort of like this: 我有一组包含嵌套列表的列表项,如下所示:

<ul class="searchselectors">
  <li class="group">Group name 1
    <ul>
      <li class="item selected">List item 1.1</li>
      <li class="item">List item 1.2</li>
      <li class="item">List item 1.3</li>
    </ul>
  </li>
  <li class="group">Group name 2
    <ul>
      <li class="item">List item 2.1</li>
      <li class="item">List item 2.2</li>
      <li class="item">List item 2.3</li>
    </ul>
  </li>
  <li class="group">Group name 3
    <ul>
      <li class="item">List item 3.1</li>
    </ul>
  </li>
</ul>

I want to cycle through all of the .item elements using up/down arrow keys (which I already have set up by using on('keydown') and catching key codes 38 and 40 ) and set .selected on the next item before or after the currently selected item, wrapping around to the top/bottom as necessary. 我想使用向上/向下箭头键(已经通过使用on('keydown')并捕获键码3840设置)循环所有.item元素,并在。之前或之后的下一项上设置.selected当前所选项目之后,根据需要环绕到顶部/底部。

Using $().next() and $().prev() will not work, since it will only work on siblings , and not on a jQuery object such as $('.searchselectors .item') .\\ 使用$().next()$().prev()无效,因为它仅适用于同级 ,而不适用于$('.searchselectors .item')类的jQuery对象。

I was working on the same problem but in my project I'm using KnockoutJS . 我当时正在处理相同的问题,但是在我的项目中,我正在使用KnockoutJS In fact, the original logic was written with pure jQuery and I refactored it with Knockout. 实际上,原始逻辑是使用纯jQuery编写的,而我使用Knockout对其进行了重构。 Here's a solution for your problem using jQuery: 这是使用jQuery解决您的问题的解决方案:

Fiddle - http://jsfiddle.net/6QN77/2/ 小提琴-http://jsfiddle.net/6QN77/2/

I didn't spend too much time cleaning up the JavaScript, but I'm leaving that to you now. 我没有花太多时间来清理JavaScript,但是现在我要把它留给您。

HTML 的HTML

<ul id="searchselectors">
  <li class="group">Group name 1
    <ul>
      <li class="item selected">List item 1.1</li>
      <li class="item">List item 1.2</li>
      <li class="item">List item 1.3</li>
    </ul>
  </li>
  <li class="group">Group name 2
    <ul>
      <li class="item">List item 2.1</li>
      <li class="item">List item 2.2</li>
      <li class="item">List item 2.3</li>
    </ul>
  </li>
  <li class="group">Group name 3
    <ul>
      <li class="item">List item 3.1</li>
    </ul>
  </li>
</ul>

jQuery jQuery的

$(function () {
    var $menu = $("#searchselectors"),
        $items = $menu.find(".item"),
        $selectedItem = $menu.find(".selected"),
        selectedIndex = $selectedItem.length - 1;

    $(document).on("keydown", function (e) {
        switch(e.keyCode) {
            case 40:  // down arrow
                $selectedItem.removeClass("selected");
                selectedIndex = (selectedIndex + 1) % $items.length;
                $selectedItem = $items.eq(selectedIndex).addClass("selected");
                break;
            case 38:  // up arrow
                $selectedItem.removeClass("selected");
                selectedIndex = (selectedIndex - 1) % $items.length;
                $selectedItem = $items.eq(selectedIndex).addClass("selected");
                break;
        }
    });
});

UPDATE : My solution revolves around getting a reference to a wrapper element ( #searchselectors ) and getting all the LI elements marked with the CSS class .item . 更新 :我的解决方案围绕获取对包装器元素( #searchselectors )的引用以及获取所有用CSS类.item标记的LI元素进行。 Next I get a reference to the currently selected element and its index. 接下来,我获得对当前选定元素及其索引的引用。 Finally, the code listens to the down and up arrow keys being pressed ( keydown ), decrementing if going up and incrementing if going up. 最后,代码侦听按下的向上和向下箭头键( keydown ),如果向上则递减,如果向上则递增。 Cycling is achieved via the modulus operator. 循环是通过模运算符实现的。 The selected item's CSS class is removed and put back. 所选项目的CSS类将被删除并放回原处。 The selected item reference is used for performance reasons so I don't have to write $items.removeClass(".selected").eq(selectedIndex).addClass("selected"); 出于性能原因,使用了选定的项目引用,因此不必编写$items.removeClass(".selected").eq(selectedIndex).addClass("selected");

In my quest to provide native JS answers to those looking for it, here is @Mario j Vargas' good answer adapted in native Javascript. 为了向寻找它的人提供本机JS答案,这是@Mario j Vargas在本机Javascript中改编的好答案。 It only takes 2 lines of extra code. 只需要两行额外的代码。

http://jsfiddle.net/kevinvanlierde/7tQSW/2/ http://jsfiddle.net/kevinvanlierde/7tQSW/2/

Only putting the JS up here, HTML is the same. 仅将JS放在这里,HTML是相同的。

(function () {
    var $menu = document.getElementById('searchselectors'),
        items = $menu.getElementsByClassName('item'),
        $selectedItem = $menu.getElementsByClassName('selected')[0],
        selectedIndex = Array.prototype.indexOf.call($selectedItem, items)+1;

    document.body.addEventListener('keydown', function (e) {
        switch(e.keyCode) {
            case 40:  // down arrow
                $selectedItem.className = $selectedItem.className.replace(' selected','');
                selectedIndex = selectedIndex < items.length - 1 ? selectedIndex + 1 : selectedIndex;
                $selectedItem = items[selectedIndex];
                $selectedItem.className += ' selected';
                break;
            case 38:  // up arrow
                $selectedItem.className = $selectedItem.className.replace(' selected','');
                selectedIndex = selectedIndex > 0 ? selectedIndex - 1 : selectedIndex;
                $selectedItem = items[selectedIndex];
                $selectedItem.className += ' selected';
                break;
        }
    }, false);
}());

Easiest way to get all the list items with class "item" is: 获取所有带有“ item”类的列表项的最简单方法是:

var items = $('.item'); 

 for (var i = 0; i < items.length; i++) {
      var item = items[i]; // iterate
 }

And then, you can select the next item from the list 然后,您可以从列表中选择下一项

OR 要么

you can do this 你可以这样做

 if (!$().next) {
    var nextUL= $().parent.find('ul')
    iterateThruList(nextUL);
 }

You could use something like 您可以使用类似

var UL = $(".searchselectors").children().length; //number of UL (group names)

to iterate through items. 遍历项目。

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

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