循环遍历JSON数据以填充HTML

时间:2014-04-29 13:45:35

标签: javascript jquery json

我有以下JSON数据,基本上我想要做的是用数组中包含的相关HTML填充几个div。

[{"id":"1","name":"profile title","html":"<h2 class=\"entry-title\" id=\"title\">Settings, Put something here?<\/h2>","typeId":"1"},
{"id":"2","name":"username","html":"<fieldset disabled><br><label for=\"nameinput\">Username<\/label><input type=\"text\" class=\"form-control\" placeholder=\"'.$name.'\" ><\/fieldset><p>","typeId":"1"},
{"id":"3","name":"date of birth","html":"<label for=\"dob\">Date of birth<\/label><input type=\"text\" name=\"dob\" class=\"form-control\" placeholder=\"01\/02\/2000\"><p>","typeId":"1"}]

这是JS:

$(document).ready(function(){
         $("#profile").one("click",function(){  

                $.ajax( {
                    type: "GET",
                    url: ROOT+"controlpanel/profile",
                    dataType:"json",
                    success: function(data){   

                            $.each(data, function(id, data1) 
                             {

                                    $('#title').html(data1.html);
                                    $('#container').append(data1.html);  
                            });
                        }


        });
    });
});

我遇到的问题是我希望ID 1中的html以不同的div进入id 2。

1 个答案:

答案 0 :(得分:1)

这个怎么样?

$(document).ready(function(){
    $("#profile").one("click",function(){  
        $.ajax( {
            type: "GET",
            url: ROOT+"controlpanel/profile",
            dataType:"json",
            success: function(data){   

                $.each(data, function(id, data1) 
                {
                    $('#title'+data.id).html(data1.html);
                    $('#container'+data.id).append(data1.html);  
                });
            }
        });
    });
});

当然,如果你的json数组可以是任意长度的,那么很可能你还没有把内容放入的元素。你可以构建html来保存你的数据在循环中。或者您可以使用隐藏的html模板,并使用jquery.clone()复制它,然后在循环中填充它。您可以使用jquery.append()将所有html片段添加到同一个容器中,可能包含在div中。您可以使用jquery('div', {})创建一个新元素,将该元素附加到某处并将您的html添加到此新div中。

有很多方法可以解决这个问题。我希望这能帮到你。如果您需要更详细的建议,请在您的问题中提供更多详细信息。

相关问题