我的布局类似于:
<div id="..."><img src="..."></div>
并希望使用jQuery选择器来选择子项 img
在 - 的里面 div
点击。
得到的 div
,我有这个选择器:
$(this)
我怎样才能得到这个孩子 img
使用选择器?
我的布局类似于:
<div id="..."><img src="..."></div>
并希望使用jQuery选择器来选择子项 img
在 - 的里面 div
点击。
得到的 div
,我有这个选择器:
$(this)
我怎样才能得到这个孩子 img
使用选择器?
jQuery构造函数接受一个名为的第二个参数 context
可用于覆盖选择的上下文。
jQuery("img", this);
哪个与使用相同 .find()
喜欢这个:
jQuery(this).find("img");
如果你想要的imgs是 只要 点击元素的直接后代,你也可以使用 .children()
:
jQuery(this).children("img");
jQuery构造函数接受一个名为的第二个参数 context
可用于覆盖选择的上下文。
jQuery("img", this);
哪个与使用相同 .find()
喜欢这个:
jQuery(this).find("img");
如果你想要的imgs是 只要 点击元素的直接后代,你也可以使用 .children()
:
jQuery(this).children("img");
你也可以使用
$(this).find('img');
这将返回所有 img
s是后代的 div
如果你需要第一个 img
你可以做到的只是一个级别
$(this).children("img:first")
如果您的DIV标记后面紧跟IMG标记,您还可以使用:
$(this).next();
该 直接 孩子是
$('> .child', 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")
您可以使用上面代码中的查找或子项。更多访问儿童 http://api.jquery.com/children/ 并找到 http://api.jquery.com/find/。 见例子 http://jsfiddle.net/lalitjs/Nx8a6/
在不知道DIV的ID的情况下,我认为你可以选择这样的IMG:
$("#"+$(this).attr("id")+" img:first")
在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
试试这段代码:
$(this).children()[0]
您可以使用以下任一方法:
1找():
$(this).find('img');
2个孩子():
$(this).children('img');
jQuery的 each
是一种选择:
<div id="test">
<img src="testing.png"/>
<img src="testing1.png"/>
</div>
$('#test img').each(function(){
console.log($(this).attr('src'));
});