![](/img/trans.png)
[英]Most efficient way to create an element from any jquery selector string
[英]What's the most efficient way to find the next element in a jQuery selector list?
我有一个任意复杂的jQuery选择器:
// a bunch of links:
var list = $('#foo').find('li.bar a, li.baz a');
我对该列表中的一个元素有一个句柄:
// the 11th such link:
var current = list.slice(10, 11);
是什么在之前和之后找到的链接最有效的方式list
? 请记住,选择器是实时的 ,并且可以在获取current
和尝试查找下一个或上一个链接之间添加或删除条目。
我能想到的最好的是O(n)遍历list
:
function adjacentInList(list, target, direction) {
var delta = (direction === 'prev' ? -1 : 1);
list = $(list);
target = $(target);
var result = null;
list.each(function(index, element) {
if (target[0] === element) {
result = list.slice(index + delta, index + delta + 1);
}
});
return result;
}
我只是分享了Steve Wellens的例子。 我有点讨厌,但保持相同的界面,并提供灵活的工作与不断变化的DOM。
主要功能:
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;
}
};
};
我确定它也是O(n)的复杂性,但使用.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;
}
有关完整示例,请参见http://jsfiddle.net/yAFr5/12/ 。
这有点笨拙,但有效:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.