简体   繁体   English

获取同一类元素内的图像属性

[英]get image attribute inside element of same class

I have following structure i want to get array of all images src attribute 我有以下结构,我想获取所有图像的src属性数组

<div id="selectable"> 
    <li class="x">
        <img src="\images\1.jpg" />
    </li>
    <li class="x">
        <img src="\images\2.jpg" />  
    </li>
    <li class="x">
        <img src="\images\3.jpg" />  
    </li>
</div>

You can do: 你可以做:

var sources = $("#selectable li img").map(function() {
    return this.src;
}).get();

In plain JS, something like this should work: 在纯JS中,类似这样的方法应该起作用:

var images = document.querySelectorAll("#selectable img");
var img_array = [];

for(var i in images) {
    img_array.push(images[i].src);
}

console.log(img_array);

one way to do this with jquery: 用jquery做到这一点的一种方法:

$('#selectable').children('li').each(
function(index){
imgSrc[index]=$(this).children('img').attr('src');
}
);

Also: 也:

var img_array = [];
$.each($("#selectable").find('li > img'),function(index,image){


    img_array.push($(image).attr("src"));

});
var srcarray=[];
$( "#selectable .x img" ).each(function( index ) {
  srcarray[index]=$(this).attr('src');
});
alert(srcarray);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM