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

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

  • fourth caption
  • fifth caption
  • sixth caption

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

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

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

 for (int i=0; i 

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

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

你怎么说出差异? 呼叫:

 alert(obj.constructor.toString()); 

第一个版本将是:

 function Object() { [native code] } 

第二:

 function Array() { [native code] } 

你可以遍历img元素:

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