是否有相对jQuery选择器这样的东西?

Eri*_*ric 14 jquery syntactic-sugar jquery-selectors

我有一个带this变量的jquery对象的引用.我正在寻找一种将子选择器应用于对象的方法.

我正在使用$(this).find('table > tbody > tr > td'),但我的目标更像是$('[Value of $(this) goes here somehow] > table > tbody > tr > td').

我知道我可以做的$(this).children('table').children('tbody').children('tr').children('td'),但我想知道,如果有一些语法糖,我可以在这里使用.

Nic*_*ver 25

你也可以在使用时从子选择器(>)开始.find(),如下所示:

$(this).find('> table > tbody > tr > td')
Run Code Online (Sandbox Code Playgroud)

这是一个经常被忽视的用例,但它对你所追求的东西非常有用.


And*_*y E 7

正如尼克所说,你可以使用find(),或者你可以使用选择器上下文:

$('> table > tbody > tr > td', this)

// Is the equivalent of
$(this).find('> table > tbody > tr > td')
Run Code Online (Sandbox Code Playgroud)

  • 无论如何,我发现 `find()` 更具解释性 (2认同)

Igo*_* G. 5

另一种方法是传递第二个参数$('selector', context),该参数定义搜索的上下文.

默认情况下,选择器在从文档根开始的DOM内执行搜索.但是,通过使用$()函数的可选第二个参数,可以为搜索提供备用上下文.

$( "div.foo" ).click(function() {
    $( "span", this ).addClass( "bar" );
});
Run Code Online (Sandbox Code Playgroud)