如何使用JQuery选择.each循环中元素的子元素?

Mar*_*rty 5 html jquery jquery-selectors

我正在尝试<img>在每个<a>具有类名的标签中选择标签customurl.

我知道我可以这样做<a>:

$(".customurl img");
Run Code Online (Sandbox Code Playgroud)

但我正在尝试弄清楚语法是什么.each样的:

$(".customurl").each(function(i)
{
    var t = $(this);

    // select child <img> within t
    // (for this iteration)
});
Run Code Online (Sandbox Code Playgroud)

这是一个HTML片段,供进一步说明:

<a class="customurl"><img src="blah" /> Some text</a>
<a class="customurl"><img src="blah" /> Some text</a>
<a class="customurl"><img src="blah" /> Some text</a>
Run Code Online (Sandbox Code Playgroud)

use*_*716 6

使用children()[docs]方法.

$(".customurl").each(function(i)
{
    var t = $(this).children('img');

});
Run Code Online (Sandbox Code Playgroud)

或者如果您要确保图像前没有文本节点(包括空格):

$(".customurl").each(function(i)
{
    var t = $(this.firstChild);

});
Run Code Online (Sandbox Code Playgroud)

...但是如果您只是要运行jQuery方法,它们会为您迭代:

$(".customurl > img").attr(/*...*/);
Run Code Online (Sandbox Code Playgroud)

这将attr()[docs]方法应用于结果中的每个元素.

此外,一些方法.attr()会接受回调作为参数.

$(".customurl > img").attr('src', function(i,src) {
     // give each <img> a calculated value for its src
    return 'some_new_value_' + i;
});
Run Code Online (Sandbox Code Playgroud)


Sam*_*iew 5

使用.find('')

$(this).find('img')
Run Code Online (Sandbox Code Playgroud)

要么

t.find('img')
Run Code Online (Sandbox Code Playgroud)

或者这也可以使用.each()的第二个参数:

$(".customurl").each(function(i, elem)
{
    $(elem).find('img')
Run Code Online (Sandbox Code Playgroud)

如果您只想要第一张图片(假设您有多张图片):

$(this).find('img:first')
Run Code Online (Sandbox Code Playgroud)

要么

$(this).find('img:first-child')
Run Code Online (Sandbox Code Playgroud)