2013-02-11 221 views
2

我想循環訪問一個數組,然後遍歷一個列表。循環遍歷數組並檢索值

我遇到的問題是每個<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> 

感謝所有幫助:)

+0

我不熟悉你的列表元素;但如果你可以使用.get(int index)函數,你會想要保持一個計數並將其用作索引。 – RyanS 2013-02-11 16:04:04

回答

2

只是這樣做:

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

$("#list span").each(function(index) { 
    $(this).append(arrValues[index]); 
}); 
1

我認爲這將是一個更簡單的方法來實現:

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

您目前擁有的是你通過數組(3次迭代)迭代的問題,每次迭代通過整個循環數量爲<span> s,因此總共有9次迭代。