試試這個。它會標記你的元素,創建一組與你的選擇器匹配的元素,並收集元素後面的所有元素。
$.fn.findNext = function (selector) {
var set = $([]), found = false;
$(this).attr("findNext" , "true");
$(selector).each(function(i , element) {
element = $(element);
if (found == true) set = set.add(element)
if (element.attr("findNext") == "true") found = true;
})
$(this).removeAttr("findNext")
return set
}
EDIT
簡單得多的解決方案使用jquerys索引方法。你需要調用該方法的元素是可選擇由相同的選擇,雖然
$.fn.findNext = function(selector){
var set = $(selector);
return set.eq(set.index(this,) + 1)
}
從這一障礙釋放功能,我們可以憂色瀏覽器擁有compareDocumentposition
$.fn.findNext = function (selector) {
// if the stack is empty, return the first found element
if (this.length < 1) return $(s).first();
var found,
that = this.get(0);
$(selector)
.each(function() {
var pos = that.compareDocumentPosition(this);
if (pos === 4 || pos === 12 || pos === 20){
// pos === 2 || 10 || 18 for previous elements
found = element;
return false;
}
})
// using pushStack, one can now go back to the previous elements like this
// $("#someid").findNext("div").remove().end().attr("id")
// will now return "someid"
return this.pushStack([ found ]);
},
EDIT 2 使用jQuery的$ .grep這非常容易。這裏是新代碼
$.fn.findNextAll = function(selector){
var that = this[ 0 ],
selection = $(selector).get();
return this.pushStack(
// if there are no elements in the original selection return everything
!that && selection ||
$.grep(selection, function(n){
return [4,12,20].indexOf(that.compareDocumentPosition(n)) > -1
// if you are looking for previous elements it should be [2,10,18]
})
);
}
$.fn.findNext = function(selector){
return this.pushStack(this.findNextAll(selector).first());
}
當壓縮變量名稱時,這成爲僅僅兩個班輪。
編輯3 使用按位運算,這個函數可能會更快?
$.fn.findNextAll = function(selector){
var that = this[ 0 ],
selection = $(selector).get();
return this.pushStack(
!that && selection || $.grep(selection, function(n){
return that.compareDocumentPosition(n) & (1<<2);
// if you are looking for previous elements it should be & (1<<1);
})
);
}
$.fn.findNext = function(selector){
return this.pushStack(this.findNextAll(selector).first());
}
的
可能重複的[jQuery來找到匹配表達式的所有先前的元件](http://stackoverflow.com/questions/322912/jquery-to-find-all-previous-elements-that-match- an-expression) – sachleen 2012-07-18 19:29:19