我是JavaScript新手,所以這可能不是最好的方法。我正在做Bellycard's web app challenge #1的樂趣。動態創建和嵌套從JSON數組的DIV項目
我查詢自己的搜索終點,返回JSON,像這樣:https://rdio-service.herokuapp.com/search?q=korn(點擊)
我得到的唯一的搜索類型:
//artist, album, tracks
var searchTypes = $.unique(data.data.map(function(d) {return d.type}));
然後我迭代searchTypes
和過濾原始data
JSON爲即searchType
。我學會了如何將.appendChild
添加到GUI上的現有項目中。但我不知道如何顯示每個searchType
下的結果。下面的代碼。
//iterate searchTypes and display them foreach searchType
for(var i = 0; i < searchTypes.length; i++)
{
var searchType = searchTypes[i];
var newDiv = document.createElement('div');
newDiv.id = searchType + "Result";
//and then, each search type should have results for their type
//select specific type for this iteration and put it in a results array
var resultsThisType = data.data.filter(function (f) {
return f.type == searchType;
});
for(var j = 0; j < resultsThisType.length; j++) {
var newP = document.createElement('p'); //put it in a 'p' item for now, for testing
newP.id = searchType + i + j;
newP.innerHTML = resultsThisType[i].name; //test
document.getElementById(searchType + "Result").appendChild(newP); //error here... what's the right approach?
}
newDiv.className = "typeResult";
newDiv.innerHTML = "<h2>" + searchType + "</h2>";
document.getElementById("results").appendChild(newDiv);
}
明白了,輸入答案... –
'document.getElementById(searchType +「Result」)'爲空,沒有.appendChild這樣的方法。 – Kyle
你可以在jsfiddle中設置它嗎? – shaN