开发者

What's the most efficient way to find the next element in a jQuery selector list?

开发者 https://www.devze.com 2023-02-21 20:51 出处:网络
I have a jQuery selector of arbitrary complexity: // a bunch of links: var list = $(\'#foo\').find(\'li.bar a, li.baz a\');

I have a jQuery selector of arbitrary complexity:

// a bunch of links:
var list = $('#foo').find('li.bar a, li.baz a');

I have a handle on one element within that list:

// the 11th such link:
var current = list.slice(10, 11);

What's the most efficient way to find the links before and after in list? Keep in mind that the selector is live and that entries may be added or removed between getting current and trying to find the next or previous link.

The best I can come up with is a O(n) traversal of list:

function adjacentInList(list, target, direction) {
  var delta = (direction === 'prev' ? -1 : 1);
  list = $(list);
  target = $(target);
  var result = null;
  lis开发者_JAVA技巧t.each(function(index, element) {
    if (target[0] === element) {
      result = list.slice(index + delta, index + delta + 1);
    }
  });
  return result;
}


I just forked Steve Wellens example. Mine is a bit nastier but maintains the same interface and offers the flexibility of working with a changing DOM.

http://jsfiddle.net/sJwJL/

Primary function:

var itr = function(selector){
    var last_element = null;
    return {
        next : function(){
            var elements = $(selector);
            var last_index = 0;
            if(last_element != null){
                elements.each(function(item){
                    if(item == last_element){
                        last_index = index+1;
                        return;
                    }
                });
            }
            last_element = $(elements[last_index]);
            return last_element;
        }
    };
};


I'm sure it's also O(n) complexity, but wouldn't the syntax would be much simpler using .index()?

function next() {
   var currList = $(list.selector),
       idx = currList.index(current);
   return idx >= 0 && idx < currList.length-1 ?
       currList.slice(idx+1,idx+2) : undefined;
}

function prev() {
   var currList = $(list.selector),
       idx = currList.index(current);
   return idx > 0 ? 
       currList.slice(idx - 1, idx) : undefined;
}

See http://jsfiddle.net/yAFr5/12/ for the full example.


This is a bit klunky but works:

http://jsfiddle.net/zHDws/

0

精彩评论

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