15

我有一个带有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'),但我想知道是否可以在这里使用一些语法糖。

4

3 回答 3

28

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

$(this).find('> table > tbody > tr > td')

这是一个经常被忽视的用例,但它非常适合您所追求的。

于 2010-08-23T10:53:00.703 回答
8

As Nick said, you can use find(), or you can use selector context:

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

// Is the equivalent of
$(this).find('> table > tbody > tr > td')
于 2010-08-23T10:56:13.520 回答
7

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

默认情况下,选择器从文档根目录开始在 DOM 中执行搜索。但是,可以使用 $() 函数的可选第二个参数为搜索提供替代上下文。

$( "div.foo" ).click(function() {
    $( "span", this ).addClass( "bar" );
});
于 2016-04-01T13:31:05.877 回答