2010-08-11 45 views
21

标记:如何在已选元素上进行子选择?

<div class="foo"> 
    <img src="loading.gif" class="loading" style="display: none;" /> 
</div> 

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(); 
}); 

回答

25
$("div[class='foo']").click(function(e) { 
    e.preventDefault(); 
    $(this).hide(); 
    $('img.loading', this).show(); 
}); 
+1

哇!您可以将上下文传递给$选择器!尼斯。 – randomguy 2010-08-11 13:37:19

+3

@randomguy:选择器上下文映射到* find()*方法,因此'$('img.loading',this)'与$(this).find('img.loading')'相同。我认为,选择器上下文更“更好”。 – 2010-08-11 13:41:03

23

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

$(this).find(".foo"); 

如果你知道你只想搜索一级儿童元素,可以用children()

$(this).children(".foo"); 
+0

我喜欢的提示儿童( “富”) – Stefan 2016-06-04 15:07:19

+0

确实是正确的 - 但根据你了解_sub selects_方式在问题标题中,初始集_元素可能成为候选人。但据我所知,'find'不会考虑后代。我不知道是否有办法在“自己或后代”中找到... – 2016-10-09 08:23:25

0

你可以使用

$(this).find("img").show(); 

$(this).find("img.loading").show();