我有一个类似于这样的布局:
<div id="..."><img src="..."></div>
我希望在单击时使用jQuery选择器选择div
内的子级img
。
要获取div
,我有以下选择器:
$(this)
我该如何使用选择器获取子元素
img
?我有一个类似于这样的布局:
<div id="..."><img src="..."></div>
我希望在单击时使用jQuery选择器选择div
内的子级img
。
要获取div
,我有以下选择器:
$(this)
img
?jQuery构造函数接受第二个参数context
,可用于覆盖选择的上下文。
jQuery("img", this);
这与使用如下的.find()
方法相同:
jQuery(this).find("img");
如果您希望获取的图片只是所点击元素的直接后代,则还可以使用.children()
方法:
jQuery(this).children("img");
$(this).find('img');
这将返回所有属于div
后代的img
元素。
$(this).children('img')
更好。例如 <div><img src="..." /><div><img src="..." /></div></div>
,因为用户可能想要查找一级图片。 - Buttle Butkus如果你需要获取第一个恰好下一级的img
,你可以这样做:
$(this).children("img:first")
如果你的 DIV 标签紧跟着 IMG 标签,你也可以使用以下代码:
$(this).next();
直接子元素是
$('> .child-class', this)
您可以按如下方式查找父级 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/
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
不知道 DIV 的 ID,我认为你可以像这样选择 IMG:
$("#"+$(this).attr("id")+" img:first")
试试这段代码:
$(this).children()[0]
1 find():
$(this).find('img');
2 children():
$(this).children('img');