代码之家  ›  专栏  ›  技术社区  ›  Eric

有没有相对jQuery选择器?

  •  13
  • Eric  · 技术社区  · 14 年前

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

    我在用 $(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') ,但我想知道这里是否有语法上的糖分。

    3 回复  |  直到 14 年前
        1
  •  26
  •   Nick Craver    14 年前

    你可以从一个 child selector ( > ) .find() 还有,像这样:

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

    这是一个经常被忽略的用例,但是它对于您所追求的东西非常有用。

        2
  •  8
  •   Andy E    14 年前

    就像尼克说的,你可以用 查找() selector context

    $('> table > tbody > tr > td', this)
    
    // Is the equivalent of
    $(this).find('> table > tbody > tr > td')
    
        3
  •  7
  •   Igor G.    9 年前

    另一种方法是传递第二个参数 $('selector', context)

    在文档根目录下。但是,可以为 使用$()函数的可选第二个参数进行搜索。

    $( "div.foo" ).click(function() {
        $( "span", this ).addClass( "bar" );
    });