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

FFi*_*ish 20 arrays jquery attributes loops push

我有这个缩略图列表,并希望将图像路径(源)推入一个数组: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>
Run Code Online (Sandbox Code Playgroud)

cle*_*tus 48

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

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

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

for (int i=0; i<tn_array.length; i++) {
  alert(tn_array[i]);
}
Run Code Online (Sandbox Code Playgroud)

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

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

你怎么说出差异?呼叫:

alert(obj.constructor.toString());
Run Code Online (Sandbox Code Playgroud)

第一个版本将是:

function Object() { [native code] }
Run Code Online (Sandbox Code Playgroud)

第二:

function Array() { [native code] }
Run Code Online (Sandbox Code Playgroud)


Fel*_*ing 5

你可以循环遍历任何img元素:

var tn_array = Array();

$('#thumbnails img').each(function() {
    tn_array.push($(this).attr('src'));
});
Run Code Online (Sandbox Code Playgroud)