如何使用JQuery在特定div中获取img

DEV*_*OPS 18 jquery jquery-selectors

我必须在特定div中获取所有图像标记ID.我怎样才能使用JQuery?

Rei*_*gel 35

var arraysOfIds = $('#particularDivId img').map(function(){
                       return this.id;
                   }).get();

// arraysOfIds has now all the id's, access it as arraysOfIds[0], arraysOfIds[1]....  
Run Code Online (Sandbox Code Playgroud)

  • 啊,很酷.我已经学习了.map()功能的新功能.但是,查看文档,为什么最后需要.get()调用.我刚刚尝试了没有它的代码,它工作正常.新手想要学习. (2认同)

Jas*_*ans 10

粗略猜测,但尝试:

var imgIds = new Array();

$("div#divID img").each(function(){
    imgIds.push($(this).attr('id'));
});
Run Code Online (Sandbox Code Playgroud)

你没有给出它的名字div,但我已经用作divIddiv的id.只需更改它即可满足您的需求.


Mar*_*ive 9

使用子选择器.所以你的说法我想要div #myDiv的所有孩子'img'元素

$("#myDiv > img").css("border", "3px double red");
Run Code Online (Sandbox Code Playgroud)

http://api.jquery.com/child-selector/