2010-10-25 17 views
1

我想使用jquery/json顯示這些數組,但我一直未定義。顯示json文件的問題

此外,我如何顯示是沒有用戶點擊「A」?

在此先感謝

== jSON file == 

// JSON 
{ 
"items": [ 
{ 
"title": "welcoem home", 
"author": "Charles Dickens" 
}, 
{ 
"title": "Harry Potter", 
"author": "J rowling" 
} 
] 
} 

== 

<script language="javascript" > 
$(document).ready(function() { 
    $('#letter-a a').click(function() { 
    $.getJSON('q3.json', function(data) { 
     $('#dictionary').empty(); 
     $.each(data, function(entryIndex, entry) { 
     var html = '<div class="entry">'; 
     html += '<h3 class="term">' + entry['title'] + '</h3>'; 
     html += '<div class="part">' + entry['author'] + '</div>'; 
     html += '<div class="definition">'; 
     html += entry['definition']; 
     if (entry['items']) { 
      html += '<div class="quote">'; 
      $.each(entry['items'], function(lineIndex, line) { 
      html += '<div class="quote-line">' + line + '</div>'; 
      }); 
      if (entry['author']) { 
      html += '<div class="quote-author">' + entry['author'] + '</div>'; 
      } 
      html += '</div>'; 
     } 
     html += '</div>'; 
     html += '</div>'; 
     $('#dictionary').append(html); 
     }); 
    }); 
    return false; 
    }); 
}); 


</script> 

<link rel="stylesheet" href="json.css" type="text/css" /> 
</head> 

<body> 
<div id="container"> 
     <div id="header"> 
     <h2>json stuff</h2> 
     </div> 

     <div class="letters"> 
       <div class="letter" id="letter-a"> 
       <h3><a href="#">A</a></h3> 
       </div>  

     </div> 
     <div id="dictionary"> 

     </div> 
</div> 

回答

0

您在這裏有問題的原因是因爲你是通過數組中的錯誤級別循環,當你叫$.each(data)

你是$.each(data)內部代碼期望是通過項目的數組循環,但實際上,它是通過data數組鍵本身,其中只有一個循環,這是items

修復很簡單:更改數據in your each()call to be data.items`。

的代碼行現在看起來是這樣的:

$.each(data.items, function(entryIndex, entry) { 

希望有所幫助。 (即使有點遲了)