开发者

Problem displaying json file

I am trying to display these arrays using jquery/json but i keep getting undefined.

Also, how can i display is without the user clicking "A" ?

thanks in advance

== 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').clic开发者_如何转开发k(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>


The reason you were having problems here is because you were looping through the wrong level in the array when you called $.each(data).

Your code inside that $.each(data) expects be looping through an array of items, but in fact, it is looping through the array keys of data itself, of which there is only one, that being items.

The fix is simple: change datain youreach()call to bedata.items`.

The line of code now looks like this:

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

Hope that helps. (even if it is a bit late)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜