繁体   English   中英

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

[英]How to select consecutive elements that match a filter

鉴于这个例子:

<img class="a" />
<img />
<img class="a" />
<img class="a" id="active" />
<img class="a" />
<img class="a" />
<img />
<img class="a" />

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

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

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

这就是我最终想出来的。

// 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);
}

对于一个后续问题,我可以看到如何通过将它变成一个带有两个参数的函数来轻松推广它:一个初始元素和一个过滤字符串 - 任何人都可以指出我正确的方向来找出如何扩展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

我相信循环是你最好的选择。 但你可以尝试,每个都是活动的,然后前后移动直到条件中断,如果设置足够大则会更快。

下面的代码将添加两个新函数,nextConsecutive()和prevConsecutive()。 他们应该做你想做的事。

$ .each(['prev','next'],function(unusedIndex,name){$ .fn [name +'Consecutive'] = function(matchExpr){

    var $all = 
        (name == 'prev')
             ? $(this).prevAll()
             : $(this).nextAll();
    if (!matchExpr)
        return $all;

    var $notMatch = $($all).not(matchExpr).filter(':first');
    if ($all.index($notMatch) != -1)
        return $allConsecutive = $all.slice(0, $all.index($notMatch));

    return $all;
};

});

代字号(〜)是兄弟选择器

$('#active ~ img.a').hide();

@Prestaul

$('#active ~ img.a')

只会选择以下兄弟姐妹,并且也包括非连续的兄弟姐妹。 文档: http//docs.jquery.com/Selectors/siblings#prevsiblings

这是另一种方法,虽然兄弟选择器的答案非常酷:

var next = $('#active').next('.a');
var prev = $('#active').prev('.a');

编辑:我重新阅读您的要求,这不是您想要的。 你可以使用nextAll和prevAll,但是那些也不会在没有类名的情况下停留在IMG上。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM