2012-10-05 40 views
3

我是jQuery的新手,每次循環都卡住了。使用foreach循環打印所有結果

我試圖從對象的變量得到的值,當我打印使用alert(),我得到的所有結果。

但是,當我試圖把它打印到我只得到最後的結果輸出到HTML而不是3的HTML,在這種情況下。

$.each(playlist, function(index, item) { 
    alert(item.title); 
    $('.playlist1').text(item.title); 
}); 

回答

4

其實,你不是停留在.each()循環,你被困在.text()

.text()替換新文本的當前文本,所以你永遠只看到在這種情況下的最後一個。可能使用.append()

你也可以以這種方式使用.text()

$('.playlist1').text(function(index, text){ 
    return text + item.title; 
}); 

假設.playlist1ulol,可以追加到它是這樣的:

$('.playlist1').append('<li>'+item.title+'</li>'); 
+0

呵呵,謝謝!你必須每天都要學習新東西,而且我只學過一門!謝謝! :) – blytung

+1

ahh,所以它是索引,thanx爲了讓它感覺出來。 :) –

+0

謝謝你們,它工作得很好。但正如我之前說過的,我對這種類型的東西不熟悉。如果我想將所有結果循環到列表項中,我該怎麼做?不要真的讓它工作。 – blytung

2

您需要使用append功能而不是text

$('.playlist1').append(item.title); 

text()用新內容替換元素的內容。 append()將新內容附加到元素的現有內容。

更新

在每個項目添加爲列表項做到這一點:

$('.playlist1').append('<li>' + item.title + '</li>'); 
+0

謝謝你們,它工作得很好。但正如我之前說過的,我對這種類型的東西不熟悉。如果我想將所有結果循環到列表項中,我該怎麼做?不要真的讓它工作。 – blytung

+0

@blytung,你會使用'append('

  • '+ item.title +'
  • ')' – ahren

    +1

    我已經更新了我的答案,顯示將內容添加爲列表項目。 –

    1

    使用警報可以中斷腳本的執行,可以考慮使用的console.log()

    console.log(item.title); 
    

    每個循環迭代非常像foreach,在這種情況下,我是迭代器,並且項目是值

    $.each(playlist, function (i, item) { 
    

    迭代時,將「class = playlist1」的每個元素的文本設置爲item.title

    $('.playlist1').text(item.title); 
    }); 
    

    雖然語法上沒有任何錯誤,但存在邏輯錯誤。也許你可以試試這個:

    var fulltext = [];//initialize empty array 
    $.each(playlist, function (i, item) { 
    fulltext.push(item.title);//iterate through playlist and collect titles 
    }); 
    $('.playlist1').text(fulltext.join(" "));//join array with titles with a blank space 
                 //and put them in class playlist1 
    

    ,你可以對列表中的項目做到這一點:

    var ul = document.createElement("ul"); 
    $.each(playlist, function (i, item) { 
    var thisLi = document.createElement("li"); 
    thisLi.innerHTML = item; 
    ul.appendChild(thisLi); 
    }); 
    $('.playlist1').append(ul); 
    
    +0

    @blytung - 查看創建列表的編輯。 –