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

编程入门 行业动态 更新时间:2024-10-26 22:21:12
本文介绍了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 源属性并推入数组

本文发布于:2023-11-12 11:36:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581392.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   属性   列表中   jQuery   img

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!