jQuery 从列表中获取 img 源属性并推入数组 [英] jQuery get img source attributes from list and push into array

查看:42
本文介绍了jQuery 从列表中获取 img 源属性并推入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个缩略图列表,并希望将图像路径(来源)推送到一个数组中:tn_array

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>

推荐答案

您可以更直接地使用 map():

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

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

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

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

但是,您可以调用 get(),这样就可以了一个严格的数组:

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

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

你如何区分?调用:

alert(obj.constructor.toString());

第一个版本是:

function Object() { [native code] }

第二个:

function Array() { [native code] }

这篇关于jQuery 从列表中获取 img 源属性并推入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆