2015-08-25 12 views
0

我想了解如何獲取我要顯示的數組列表。 我目前使用一個.each函數來獲取從數組列表中,但是當我使用的.text填充span標籤帶班只顯示最後一個項目

這裏是我的jQuery代碼

$.each (json.consultants, function(i) { 
    console.log(json.consultants[i].firstname) 
    $('.consultantsfirstname').text(json.consultants[i].firstname) 
    $('.consultantslastname').text(json.consultants[i].lastname) 

}) 

我想找到顯示列表中顯示的數組 不只是最後一個。

+2

這是不會因爲你的工作」每次重寫文本。你需要將它追加到一個字符串中,或​​者你可以創建一個有序列表,然後將它附加到你的'span'中。 – Sushil

+0

能否詳細說明一下?我是.appendTto()的家常便飯,但我不會在那裏放置它。如果這是有道理的@Sushil –

+0

另外,你確定你想使用$('。consultantsfirstname')?這有可能不是唯一的,也是每次都會覆蓋的原因。 –

回答

1

您每次都覆蓋文字。

嘗試:

$.each (json.consultants, function(i) { 
console.log(json.consultants[i].firstname) 
$('.consultantsfirstname').text($('.consultantsfirstname').text() + json.consultants[i].firstname) 
$('.consultantslastname').text($('.consultantsfirstname').text() + json.consultants[i].lastname) 

}) 

如果你只是想反正顯示的數據,你可以這樣做:

$.each (json.consultants, function(i) { 
console.log(json.consultants[i].firstname) 
$('#list').html($('#list').html() + json.consultants[i].firstname); 
$('#list').html($('#list').html() + ' '); 
$('#list').html($('#list').html() + json.consultants[i].lastname); 
$('#list').html($('#list').html() + '<br />'); 
}); 

隨着HTML

<div id="list" /> 
+0

但是,它可以將它們分組到同一個跨度中,合併爲一個 –

+0

右,$('。consultantsfirstname')不是唯一的。它會每次返回相同的跨度。我認爲你的意思是$('。'+ json.consultants [i] .firstname) –

+0

在第二個.text或first.text? –

相關問題