如何使用jQuery选择单个子元素?我看过Traversing API,知道我可以选择所有直接的子img
元素,如下所示:
$(this).children('img');
为了选择第一个子img
元素,我可以使用下面这样的下标:
$(this).children('img')[0];
但我想我有点惊讶我不能这么做:
$(this).child('img'); // no subscript, returns single element
还是我错过了什么?
发布于 2009-09-24 20:57:03
我认为你想要做的是:
$(this).children('img').eq(0);
这将为您提供一个包含第一个img元素的jquery对象,而
$(this).children('img')[0];
将为您提供img元素本身。
发布于 2009-09-24 20:58:51
也许是这样吧?
$('img', this)[0]
发布于 2020-11-21 07:22:36
你可以只使用CSS selector和jQuery来定位第一个子元素:
$(this).children('img:nth-child(1)');
如果您想要针对第二个子元素,只需将1改为2:
$(this).children('img:nth-child(2)');
以此类推..
如果你想定位更多的元素,你可以使用for循环:
for (i = 1; i <= $(this).children().length; i++) {
let childImg = $(this).children("img:nth-child("+ i +")");
// Do stuff...
}
https://stackoverflow.com/questions/1474089
复制相似问题