循环遍历数组并检索值
问题描述:
我想循环访问一个数组,然后遍历一个列表。循环遍历数组并检索值
我遇到的问题是每个<li>
整个数组都被追加,但我需要发生的是数组的索引(0)被添加到第一个li,index(1)到第二个li等等上。
代码:
// Create our test array.
var arrValues = [ "one", "two", "three" ];
// Loop over each value in the array.
$.each(arrValues,function(intIndex, objValue){
$("#list span").each(function() {
$(this).append(objValue);
});
});
电流输出:
<ul id="list">
<li>Content 1 here<span>onetwothree</span></li>
<li>Content 2 here<span>onetwothree</span></li>
<li>Content 3 here<span>onetwothree</span></li>
</ul>
所需的输出:
<ul id="list">
<li>Content 1 here<span>one</span></li>
<li>Content 2 here<span>two</span></li>
<li>Content 3 here<span>three</span></li>
</ul>
感谢所有帮助:)
答
只是这样做:
var arrValues = [ "one", "two", "three" ];
$("#list span").each(function(index) {
$(this).append(arrValues[index]);
});
答
我认为这将是一个更简单的方法来实现:
$("#list span").each(function(intIndex, objValue){
$(this).append(arrValues[intIndex]);
});
您目前拥有的是你通过数组(3次迭代)迭代的问题,每次迭代通过整个循环数量为<span>
s,因此总共有9次迭代。
我不熟悉你的列表元素;但如果你可以使用.get(int index)函数,你会想要保持一个计数并将其用作索引。 – RyanS 2013-02-11 16:04:04