【问题标题】:each item in an array into each matched element数组中的每个项目到每个匹配的元素中
【发布时间】:2013-04-18 10:52:17
【问题描述】:

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

感谢任何可以提供帮助的人!

【问题讨论】:

    标签: jquery arrays object loops each


    【解决方案1】:

    你可以使用索引:

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

    【讨论】:

    • 非常感谢,完全有道理,但没有帮助我无法到达那里。非常感谢。
    • @Blazemonger,也谢谢你!
    猜你喜欢
    • 1970-01-01
    • 2013-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    • 2014-06-28
    • 1970-01-01
    相关资源
    最近更新 更多