如何对已选择的元素进行子选择?

ran*_*guy 26 jquery jquery-selectors

标记:

<div class="foo">
    <img src="loading.gif" class="loading" style="display: none;" />
</div>
Run Code Online (Sandbox Code Playgroud)

JS:

$("div[class='foo']").click(function(e) {
    e.preventDefault();
    $(this).hide();
    $(/* somehow select the loading img of exactly this div with class foo (not others) */).show();
});
Run Code Online (Sandbox Code Playgroud)

sim*_*rsh 30

$("div[class='foo']").click(function(e) {
    e.preventDefault();
    $(this).hide();
    $('img.loading', this).show();
});
Run Code Online (Sandbox Code Playgroud)

  • @randomguy:Selector上下文映射到*find()*方法,因此`$('img.loading',this)`与`$(this).find('img.loading')`相同.我认为选择器上下文更"好". (4认同)
  • 哇!您可以将上下文传递给$ -selector!尼斯. (2认同)

mat*_*t b 26

如果你想要给定元素的任何后代,你可以使用find():

$(this).find(".foo");
Run Code Online (Sandbox Code Playgroud)

如果您知道只想搜索第一级子元素,则可以使用children():

$(this).children(".foo");
Run Code Online (Sandbox Code Playgroud)