2014-04-29 55 views
0

我有下面的JSON數據,基本上我想要做的是用數組中包含的相關HTML填充幾個div。儘管JSON數據循環來填充HTML

[{"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.

+0

數組中的每個元素都應該轉到不同的div上嗎? – milagvoniduak

回答

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中。

有很多方法來處理這個問題。我希望這可以幫助你。如果您需要更詳細的建議,請在您的問題中提供更多詳細信息。