2013-04-24 254 views
1

每個項目我使用$ .getJSON返回一個簡單的數組,例如:在陣列到每個匹配元素

["5","10","15","20"] 

那麼我想每個值的前面加上一個元素。我知道如何通過數組迭代和執行功能,如:

$(data).each(function(i,data){  
console.log(data);   
}); 

我想不通的是如何在陣列中的每個項目,將其添加到每一個匹配元素,如:

$('#element h2').each(function(){ 
    $(this).before('<h1>' + data + '</h1>') 
}); 

就是我希望實現的是:

<div id="element"> 
    <h1>5</h1> 
    <h2>Apples</h2> 
    <h1>10</h1> 
    <h2>Oranges</h2> 
    <h1>15</h1> 
    <h2>Bananas</h2> 
    <h1>20</h1> 
    <h2>Kiwis</h2> 
</div> 

謝謝你的人,可以幫助!

回答

2

您可以使用索引:

$('#element h2').each(function(index) { 
    $(this).before('<h1>' + data[index] + '</h1>') 
}); 
+0

另一種稍微複雜的方法:http://jsfiddle.net/mblase75/nqBJh/ – Blazemonger 2013-04-24 18:42:31

+0

非常感謝你,非常有意義,但我不能沒有到達那裏幫幫我。我非常感激。 – 2013-04-24 19:30:33

+0

@Blazemonger,謝謝! – 2013-04-24 19:31:58