2013-04-04 154 views
3

所以我現在加載文本和圖像的單獨精緻漂亮JSON文件,這就是我所做的,以測試它是否會工作只是一個簡單的例子:加載圖像使用jQuery

outputc+="<li>" 
    outputc+=this.name+" "+this.price+"</li>"; 
    $('#featured').append(outputc); 
    $("<img/>").attr('src',this.images).appendTo('#featured'); 

使用上面的代碼工作完美,但是我需要爲這兩種用列表來包裹着,所以我做了一些搜索,我發現這一點:

$(document).ready(function(){ 

//loading json file 

var url = "shoppingItems.json"; 

$.getJSON(url,function(json){ 


    $.each(json.shoppingItem,function() 
    { 
     var output ='<li><img src= "'+this.images+'" alt ="'+this.name+'"></li>'; 
    }); 

    $('.items').append(output); 
}); 
}); 

以上的jQuery沒有帶回任何東西,有我的json文件沒有任何問題,因爲它已被驗證,並且代碼可以工作,如果我sim一般警惕它。這可能是我必須做錯我的輸出腳本,我看不到。

我的JSON文件可以在這裏找到:Json file not loading or showing alerts

回答

7

既然你聲明它的回調函數內爲var output,該output變量是局部的回調函數,一旦循環爲消失。即使情況並非如此,使用=運算符將意味着每次迭代都會覆蓋以前的值。

試試這個:

var output = ""; // initialize it outside the loop 
$.each(json.shoppingItem,function() 
{ 
    output += '<li><img src= "'+this.images+'" alt ="'+this.name+'"></li>'; 
}); 
$('.items').append(output); 

http://jsfiddle.net/mblase75/zB5fv/

+0

謝謝@Blazemonger,排序追加必須是內循環,以顯示它不應該需要是所有圖像 – 2013-04-04 17:01:37

+0

。你的JSON比你提供的樣本大嗎? – Blazemonger 2013-04-04 17:06:12

+0

是的,這可能是它需要在循環之外的原因 – 2013-04-04 17:12:15