存储所选对象后如何应用其他选择器

xmo*_*oex 4 javascript jquery jquery-selectors

我想重新使用jQuery选择来进行进一步的子选择.这是我的例子:

if ($('#thisId > .thatClass').length > 0) {
    return $('#thisId > .thatClass > a.thatOtherClass').attr('id');
}
Run Code Online (Sandbox Code Playgroud)

当我广泛使用选择时,我希望(至少出于可读性原因)将代码缩短为类似于此:

var selection = $('#thisId > .thatClass');
if (selection.length > 0) {
    var furtherSelection = selection.filter('> a.thatOtherClass');
    return furtherSelection.attr('id');
}
Run Code Online (Sandbox Code Playgroud)

试着这个我得到一个错误:

TypeError:FurtherSelection.attr(...)未定义

显然我有些不对劲,也许有人有想法?

Arc*_*her 6

我们children()改为......

var selection = $('#thisId > .thatClass');
if (selection.length > 0)
{
    return selection.children('a.thatOtherClass').attr('id');
}
Run Code Online (Sandbox Code Playgroud)

我已经使用了,children()因为>选择器的使用将被弃用(根据下面的评论).

如果你不是专门寻找儿童元素那么你可以这样使用find()......

var selection = $('#thisId > .thatClass');
if (selection.length > 0)
{
    return selection.find('a.thatOtherClass').attr('id');
}
Run Code Online (Sandbox Code Playgroud)