如何选择与过滤器匹配的连续元素

nic*_*ckf 7 javascript jquery

鉴于这个例子:

<img class="a" />
<img />
<img class="a" />
<img class="a" id="active" />
<img class="a" />
<img class="a" />
<img />
<img class="a" />
Run Code Online (Sandbox Code Playgroud)

(我刚刚使用img标签作为示例,这不是我的代码中的内容)

使用jQuery,你如何选择与#active相邻的类"a"的img标签(在这个例子中是中间四个)?

您可以通过循环遍历所有以下和前面的元素来相当容易地做到这一点,当过滤条件失败时停止,但我想知道jQuery是否可以本机化?

nic*_*ckf 4

这就是我最终想到的。

// 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);
}
Run Code Online (Sandbox Code Playgroud)

对于后续问题,我可以看到如何通过将其变成一个带有两个参数的函数来轻松地概括这一点:一个初始元素和一个过滤字符串 - 任何人都可以为我指出正确的方向以找出如何扩展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');
    }
}
Run Code Online (Sandbox Code Playgroud)

--

编辑:我现在已经将其整合到一个插件中。如果您有兴趣,请查看http://plugins.jquery.com/project/Adjacent 。