jQuery get img source attributes from list and push into array

寵の児 提交于 2019-12-29 14:17:07

问题


I have this thumbnail list and would like push the image paths (sources) into an array: tn_array

<ul id="thumbnails">
    <li><img src="somepath/tn/004.jpg" alt="fourth caption" /></a></li>
    <li><img src="somepath/tn/005.jpg" alt="fifth caption" /></a></li>
    <li><img src="somepath/tn/006.jpg" alt="sixth caption" /></a></li>
</ul>

回答1:


You can create the array of src attributes more directly using map():

var tn_array = $("#thumbnails img").map(function() {
  return $(this).attr("src");
});

Edit: tn_array is an object here rather than a strict Javascript array but it will act as an array. For example, this is legal code:

for (int i=0; i<tn_array.length; i++) {
  alert(tn_array[i]);
}

You can however call get(), which will make it a strict array:

var tn_array = $("#thumbnails img").map(function() {
  return $(this).attr("src");
}).get();

How do you tell the difference? Call:

alert(obj.constructor.toString());

The first version will be:

function Object() { [native code] }

The second:

function Array() { [native code] }



回答2:


You can loop through ever img element:

var tn_array = Array();

$('#thumbnails img').each(function() {
    tn_array.push($(this).attr('src'));
});


来源:https://stackoverflow.com/questions/2355025/jquery-get-img-source-attributes-from-list-and-push-into-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!