2014-02-11 14 views
1

如何使用jquery循環雖然我的圖像&使用「標題」&「src」值創建一個數組?如何使用jquery創建我的圖像數組?

這是我的圖片列表:

<div id="myImages"> 
    <img data-title="1" src="1.jpg" alt=""> 
    <img data-title="2" src="2.jpg" alt=""> 
    <img data-title="3" src="3.jpg" alt=""> 
    <img data-title="4" src="4.jpg" alt=""> 
</div> 

這是我需要我的數組是:

[ { "title" : "1", "image" : "1.jpg", }, { "title" : "2", "image" : "2.jpg", }, { "title" : "3", "image" : "3.jpg", }, { "title" : "4", "image" : "4.jpg", } ] 
+0

僅供參考,數組的數組看起來像這樣:'[[1,2,3],[2,3,4],[2,34,55 ]]'而不是'[{1,2,3},{2,3,4},{2,34,55}]''。 – Avisari

回答

4

使用.map()轉換了一組DOM元素,以不同的表現

var array = $('#myImages img').map(function() { 
    var $this = $(this); 
    return { 
     title: $this.data('title'), 
     image: $this.attr('src') 
    } 
}).get(); 

演示:Fiddle

1

嘗試這種情況:

var data = []; 

$('#myImages img').each(function() { 
    var img = {title: $(this).data('title'), image: $(this).attr('src')}; 
    data[data.length] = img; 
}); 
1
var imageArray = []; 
$('#myImages img').each(function() { 
    imageArray.push({title: $(this).data('title'), image: $(this).attr('src')}); 
}); 
相關問題