これが私が最終的に思いついたものです。
// here's our active element.
var $active = $('#active');
// here is the filter we'll be testing against.
var filter = "img.a";
// $all will be the final jQuery object with all the consecutively matched elements.
// start it out by populating it with the current object.
var $all = $active;
for ($curr = $active.prev(filter); $curr.length > 0; $curr = $curr.prev(filter)) {
$all = $all.add($curr);
}
for ($curr = $td.next(filter); $curr.length > 0; $curr = $curr.next(filter)) {
$all = $all.add($curr);
}
フォローアップの質問については、初期要素とフィルター文字列の2つの引数を取る関数にすることで、これを簡単に一般化できることがわかりました。誰でも正しい方向に向けて、拡張する方法を見つけることができます。そのような関数を追加するjQueryオブジェクト?
編集:それ以来、each()関数がいくつかの目的のためにこれをかなりうまく行うことを発見しました。私自身の場合、これらすべての要素に対して単一のjQueryオブジェクトが必要なため、うまく機能しませんが、それぞれを異なる目的で使用する方法を次に示します(この例では、連続する「.a」要素を非表示にします:)
$('#active')
.nextAll()
.each(hideConsecutive)
.end()
.prevAll()
.each(hideConsecutive)
;
function hideConsecutive(index, element) {
var $e = $(element);
if (!$e.is(".a")) {
return false; // this stops the each function.
} else {
$e.hide('slow');
}
}
-
編集:これをプラグインにまとめました。興味がある場合は、http://plugins.jquery.com/project/Adjacentをご覧ください。