jQuery 从列表中获取 img 源属性并推入数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2355025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:19:02  来源:igfitidea点击:

jQuery get img source attributes from list and push into array

jqueryarraysloopsattributespush

提问by FFish

I have this thumbnail list and would like push the image paths (sources) into an array: tn_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>

回答by cletus

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

您可以使用map()以下命令更直接地创建 src 属性数组:

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

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

编辑:tn_array这里是一个对象,而不是一个严格的 Javascript 数组,但它将充当一个数组。例如,这是合法代码:

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:

但是get(),您可以调用,这将使它成为一个严格的数组:

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] }

回答by Felix Kling

You can loop through ever imgelement:

您可以遍历 everimg元素:

var tn_array = Array();

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