Hãy thử điều này. Nó sẽ đánh dấu Element của bạn, tạo một tập hợp các yếu tố phù hợp với bộ chọn của bạn và thu thập tất cả các yếu tố từ tập hợp sau phần tử của bạn.
$.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
đơn giản hơn nhiều giải pháp sử dụng jquerys phương pháp chỉ số. các yếu tố bạn gọi phương thức từ nhu cầu để được lựa chọn bằng cách chọn tương tự mặc dù
$.fn.findNext = function(selector){
var set = $(selector);
return set.eq(set.index(this,) + 1)
}
để giải phóng hàm từ tàn tật này, chúng ta có thể youse các trình duyệt sở hữu 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 điều này dễ dàng hơn nhiều khi sử dụng $ .grep của jQuery. đây là mã mới
$.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());
}
khi nén tên biến này trở thành hai lớp lót.
Chỉnh sửa 3 sử dụng thao tác bitwise, chức năng này thậm chí có thể nhanh hơn?
$.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());
}
có thể trùng lặp của [jQuery để tìm tất cả các phần tử trước khớp với biểu thức] (http://stackoverflow.com/questions/322912/jquery-to-find-all-previous-elements-that-match- an-expression) – sachleen