数组中的每个项目都放入每个匹配的元素中

时间:2013-04-24 18:32:17

标签: jquery arrays object loops each

我使用$ .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>

感谢任何有帮助的人!

1 个答案:

答案 0 :(得分:2)

您可以使用索引:

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