我有一个类似的布局:

<div id="..."><img src="..."></div>

并希望使用jQuery选择器在单击时选择div中的子img。

为了得到div,我有一个选择器:

$(this)

如何使用选择器获取子img?


当前回答

直接子女是

$('> .child-class', this)

其他回答

您也可以使用

$(this).find('img');

这将返回作为div后代的所有img

在jQuery中引用子级的方法。我在下面的jQuery中总结了它:

$(this).find("img"); // any img tag child or grandchild etc...   
$(this).children("img"); //any img tag child that is direct descendant 
$(this).find("img:first") //any img tag first child or first grandchild etc...
$(this).children("img:first") //the first img tag  child that is direct descendant 
$(this).children("img:nth-child(1)") //the img is first direct descendant child
$(this).next(); //the img is first direct descendant child

jQuery构造函数接受第二个名为context的参数,该参数可用于重写选择的上下文。

jQuery("img", this);

这与像这样使用.find()相同:

jQuery(this).find("img");

如果所需的img只是所单击元素的直接后代,则还可以使用.children():

jQuery(this).children("img");

如果你需要得到第一个正好向下一级的img,你可以这样做

$(this).children("img:first")

不知道DIV的ID,我想您可以这样选择IMG:

$("#"+$(this).attr("id")+" img:first")