2010-08-11 17 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();