从json文件中检索数据以创建滑块

时间:2013-12-24 04:35:15

标签: javascript jquery json

我有JSON文件,代码如下所示。我尝试检索它的数据以创建滑块元素。

这是JSON对象。

{
"slider":[{
    "img"    : "images/1.jpg",
    "title"  : "Beady little eyes",
    "expert" : "Little birds pitch by my doorstep"
},

{
    "img"    : "images/2.jpg",
    "title"  : "Beady little eyes",
    "expert" : "Little birds pitch by my doorstep"
},

{
    "img"    : "images/3.jpg",
    "title"  : "Beady little eyes",
    "expert" : "Little birds pitch by my doorstep"
},

{
    "img"    : "images/4.jpg",
    "title"  : "Beady little eyes",
    "expert" : "Little birds pitch by my doorstep"
}

]}

我使用下面的jquery代码从JSON检索数据并生成html。

$.getJSON('data.json', function(data){
        $('.slider').append('<ul/>');

            $.each(data, function(key, val){

                for(var i = 0; i < val.length; i++ ){

                    var mhtml = '<li><div class="bannerImg"><img src="'+val[i].img+'" /></div>';
                        mhtml += '<h1 class="title">'+val[i].title+'</h1>';
                        mhtml += '<p class="expert">'+val[i].expert+'</p>';
                        mhtml += '</li>';


                    $('.slider ul').append( $(mhtml) );
                }   
            });


        });

有没有更好的方法来做到这一点。因为它还没有预加载器。

1 个答案:

答案 0 :(得分:2)

尝试这样的事情

$(function(){
    var json = {
        "slider":[{
            "img"    : "images/1.jpg",
            "title"  : "Beady little eyes",
            "expert" : "Little birds pitch by my doorstep"
        },
        {
            "img"    : "images/2.jpg",
            "title"  : "Beady little eyes",
            "expert" : "Little birds pitch by my doorstep"
        },
        {
            "img"    : "images/3.jpg",
            "title"  : "Beady little eyes",
            "expert" : "Little birds pitch by my doorstep"
        },
        {
            "img"    : "images/4.jpg",
            "title"  : "Beady little eyes",
            "expert" : "Little birds pitch by my doorstep"
        }]};

    // if you are getting json like above response in ajax
    // then simply retrive slider and iterate over it
    var mhtml = '';
    $.each(json.slider, function(key, val){
        mhtml += '<li><div class="bannerImg"><img src="'+val.img+'" /></div>';
        mhtml += '<h1 class="title">'+val.title+'</h1>';
        mhtml += '<p class="expert">'+val.expert+'</p>';
        mhtml += '</li>';
    });
    var $ul = $('<ul>').append($(mhtml));// append DOM only one time.
    $('.slider').append($ul);
})

<强>替代

    var mhtml = '<ul>';
    $.each(json.slider, function(key, val){
        mhtml += '<li><div class="bannerImg"><img src="'+val.img+'" /></div>';
        mhtml += '<h1 class="title">'+val.title+'</h1>';
        mhtml += '<p class="expert">'+val.expert+'</p>';
        mhtml += '</li>';
    });
    mhtml += '</ul>';
    $('.slider').append($(mhtml));// append DOM only one time.