问:
我有一个类似于这样的布局:
并希望使用 jQuery 选择器在点击时选择 div 内的子 img。
要获得 div,我有这个选择器:
$(this)
如何使用选择器获取子 img?
答1:
huntsbot.com提供全网独家一站式外包任务、远程工作、创意产品分享与订阅服务!
jQuery 构造函数接受名为 context 的第二个参数,该参数可用于覆盖选择的上下文。
jQuery("img", this);
这与像这样使用 .find() 相同:
jQuery(this).find("img");
如果您想要的 imgs only 是点击元素的直接后代,您也可以使用 .children():
jQuery(this).children("img");
对于它的价值: jQuery("img", this) 在内部转换为: jQuery(this).find("img") 所以第二个稍微快一点。 :)
答2:
huntsbot.com汇聚了国内外优秀的初创产品创意,可按收入、分类等筛选,希望这些产品与实践经验能给您带来灵感。
你也可以使用
$(this).find('img');
这将返回 div 的后代的所有 img
在一般情况下,似乎 $(this).children('img') 会更好。例如 因为大概用户想要找到 1 级 imgs。
答3:
huntsbot.com聚合了超过10+全球外包任务平台的外包需求,寻找外包任务与机会变的简单与高效。
如果您需要获得恰好下降一级的第一个 img,您可以这样做
$(this).children("img:first")
答4:
与HuntsBot一起,探索全球自由职业机会–huntsbot.com
如果您的 DIV 标签紧跟在 IMG 标签之后,您还可以使用:
$(this).next();
.next() 真的很脆弱,除非你总能保证元素会是下一个元素,否则最好使用不同的方法。在这种情况下,IMG 是 div 的后代,而不是兄弟。
答5:
huntsbot.com洞察每一个产品背后的需求与收益,从而捕获灵感
直系子女是
$('> .child-class', this)
答6:
huntsbot.com汇聚了国内外优秀的初创产品创意,可按收入、分类等筛选,希望这些产品与实践经验能给您带来灵感。
您可以找到父 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 元素,如下所示
那么你不能使用上面的代码来查找第二个 img 元素的 alt 值。所以你可以试试这个:
$(this).find("img:last-child").attr("alt")
OR
$(this).children("img:last-child").attr("alt")
此示例显示了如何在父对象中找到实际对象的一般想法。您可以使用类来区分您孩子的对象。这既简单又有趣。 IE
您可以按以下方式执行此操作:
$(this).find(".first").attr("alt")
更具体为:
$(this).find("img.first").attr("alt")
您可以使用 find 或 children 作为上述代码。如需更多信息,请访问儿童 http://api.jquery.com/children/ 和查找 http://api.jquery.com/find/。参见示例 http://jsfiddle.net/lalitjs/Nx8a6/
答7:
huntsbot.com精选全球7大洲远程工作机会,涵盖各领域,帮助想要远程工作的数字游民们能更精准、更高效的找到对方。
在 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
答8:
huntsbot.com全球7大洲远程工作机会,探索不一样的工作方式
在不知道 DIV 的 ID 的情况下,我认为您可以像这样选择 IMG:
$("#"+$(this).attr("id")+" img:first")
这可能确实有效,但这有点像鲁布·戈德堡的回答:)
答9:
huntsbot.com高效搞钱,一站式跟进超10+任务平台外包需求
试试这个代码:
$(this).children()[0]
@rémy:这甚至不是有效的语法。 (花了整整 2 年的时间让任何人注意到......)
答10:
huntsbot.com提供全网独家一站式外包任务、远程工作、创意产品分享与订阅服务!
您可以使用以下任一方法:
1 查找():
$(this).find('img');
2 个孩子():
$(this).children('img');
答11:
huntsbot.com洞察每一个产品背后的需求与收益,从而捕获灵感
jQuery 的 each 是一种选择:
$('#test img').each(function(){
console.log($(this).attr('src'));
});
原文链接:https://www.huntsbot.com/qa/5DxO/how-to-get-the-children-of-the-this-selector?lang=zh_CN&from=csdn
huntsbot.com汇聚了国内外优秀的初创产品创意,可按收入、分类等筛选,希望这些产品与实践经验能给您带来灵感。