2

我正在尝试遍历一个数组,然后遍历一个列表。

我遇到的问题是每个<li>整个数组都被附加,但我需要发生的是将数组的索引(0)添加到第一个 li,将索引(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>

感谢任何帮助:)

4

2 回答 2

2

只需这样做:

var arrValues = [ "one", "two", "three" ];

$("#list span").each(function(index) {
    $(this).append(arrValues[index]);
});
于 2013-02-11T16:05:56.023 回答
1

我认为这将是一种更简单的实现方式:

    $("#list span").each(function( intIndex, objValue ){
        $(this).append(arrValues[intIndex]);
    });

您当前遇到的问题是您正在遍历数组( 3 次迭代),并且每次迭代都遍历整个<span>s 数,因此总共进行了 9 次迭代。

于 2013-02-11T16:10:32.727 回答