-2

我对 JSON 有疑问,现在我需要将 JSON 数据包含到 HTML 中他们

怎么解决呢?

$(document).ready(function () {
    $.getJSON('data.json', function (data) {
        $('#content').empty();
        $.each(data, function (entryIndex, entry) {
            var html = '<div class="data" id="' + entry['number'] + '">';
            html += '<b>' + entry['number'] + '</b>';
            html += '<div class="product">' + entry['product'] + '</div>';
            html += '<div class="price">' + entry['price'] + ' eur</div>';
            html += '<section class="image"><img alt="' + entry['product'] + '" src="' + entry['image'] + '"/></section>';
            if (entry['ingredients']) {
                html += '<section class="ingredients">';
                html += '<ul>';
                $.each(entry['ingredients'], function (colorIndex, ingredients) {
                    html += '<li>' + ingredients + '</li>';
                });
                html += '</ul>';
                html += '</section>';
            }
            $('#content').append(html);
        });
    });
    return false;
});
4

1 回答 1

0

在外面声明html变量$.each()并将下面的行放在外面$.each()

$('#content').append(html);

而且,关闭你的<div>IF condition

 var html = '';
 $.each(data, function(entryIndex, entry){
        html += '<div class="data" id="' + entry['number'] + '">';                     
        html += '<b>' + entry['number'] + '</b>';
        html += '<div class="product">' + entry['product'] + '</div>';  
        html += '<div class="price">' + entry['price'] + ' eur</div>';              
        html += '<section class="image"><img alt="' + entry['product'] + '" src="' + entry['image'] + '"/></section>';
        if(entry['ingredients']){
            html += '<section class="ingredients">';                                            
            html += '<ul>';
            $.each(entry['ingredients'],function(colorIndex, ingredients){
                html += '<li>' + ingredients + '</li>';                        
            }); 
            html += '</ul>';                        
            html += '</section>';
        }
        html += '</div>';
    });  
   $('#content').append(html);
于 2013-10-04T11:17:13.410 回答