如何获取$(this)选择器的子元素?

2410

我有一个类似于这样的布局:

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

我希望在单击时使用jQuery选择器选择div内的子级img

要获取div,我有以下选择器:

$(this)

我该如何使用选择器获取子元素img
19个回答

2976

jQuery构造函数接受第二个参数context,可用于覆盖选择的上下文。

jQuery("img", this);

这与使用如下的.find()方法相同:

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

如果您希望获取的图片只是所点击元素的直接后代,则还可以使用.children()方法:

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

589
就目前而言: jQuery("img", this) 在内部被转换为: jQuery(this).find("img")因此,第二个略微更快一些。 :) - Paul Irish

494
您也可以使用。
$(this).find('img');

这将返回所有属于div后代的img元素。


1
通常情况下,似乎 $(this).children('img') 更好。例如 <div><img src="..." /><div><img src="..." /></div></div>,因为用户可能想要查找一级图片。 - Buttle Butkus

148

如果你需要获取第一个恰好下一级的img,你可以这样做:

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

82

如果你的 DIV 标签紧跟着 IMG 标签,你也可以使用以下代码:

$(this).next();

17
如果不能保证元素总是下一个元素,那么使用.next()方法会非常脆弱,最好使用另一种方法。在这种情况下,IMG是DIV的后代而不是同级元素。 - LocalPCGuy

78

直接子元素是

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

57

您可以按如下方式查找父级 div 中的所有 img 元素

$(this).find('img') or $(this).children('img')

如果你想要一个特定的img元素,可以像这样编写

$(this).children('img:nth(n)')  
// where n is the child place in parent list start from 0 onwards

您的div仅包含一个img元素。因此,以下是正确的:

 $(this).find("img").attr("alt")
                  OR
  $(this).children("img").attr("alt")

但是如果您的 div 包含更多像下面这样的 img 元素

<div class="mydiv">
    <img src="test.png" alt="3">
    <img src="test.png" alt="4">
</div>

那么您无法使用上面的代码来查找第二个 img 元素的 alt 值。您可以尝试这样做:

然后,您可以尝试使用以下代码:

 $(this).find("img:last-child").attr("alt")
                   OR
 $(this).children("img:last-child").attr("alt")

这个例子展示了如何在父对象中找到实际的对象。您可以使用类来区分您的子对象。这很容易和有趣。例如:

这个例子展示了如何在父对象中找到实际的对象。您可以使用类来区分您的子对象。这很容易和有趣。例如:
<div class="mydiv">
    <img class='first' src="test.png" alt="3">
    <img class='second' src="test.png" alt="4">
</div>

您可以按照以下步骤进行:

 $(this).find(".first").attr("alt")

并更加具体,如下:

 $(this).find("img.first").attr("alt")

您可以使用上述代码中的 find 或 children 方法。更多信息请参见 Childrenhttp://api.jquery.com/children/ 和 Findhttp://api.jquery.com/find/。 请查看示例http://jsfiddle.net/lalitjs/Nx8a6/


37

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

32

不知道 DIV 的 ID,我认为你可以像这样选择 IMG:

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

54
这个方法可能真的可行,但有点像卢布·戈尔德伯格式的答案 :) - Scott Evernden

31

试试这段代码:

$(this).children()[0]

17
@rémy: 这甚至不是有效的语法。(花了整整两年才有人注意到...) - BoltClock

25
你可以使用以下任一方法:

1 find():

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

2 children():


两个 children() 方法:
$(this).children('img');

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接