如何单独为每个div添加数据

时间:2015-12-08 07:46:38

标签: javascript jquery html

简单但我不知道该怎么做。我试图分别为每个div附加数据$。每个函数都循环并将整个数据分配给同一个div。 这是我的两个div。

     <div class="div1">
                    <div class="div2">
         // whole javascript code is here
                </div>
         </div>

整个代码是这样的:

   <script type="text/javascript">
          $(document).ready(function () {
              $.getJSON("/Post/GetPosts", null, function(data)
              {
               htmlResultData="<br /> " + "Users received from server: " + "<br />";
               $.each(data, function (i, item)
               {
              htmlResultData += item.PostedByName + "<img src='" + item.PostedByAvatar + "'height='100' width='100'/> ";
               });
                $(".div2").empty().append(htmlResultData);
            //however, i have tried to return false here but still same result
               return false;
             });
           });

Div1包含特定div2的外部CSS。我想为服务器返回的每个数据生成多个div2。我尝试过使用return false但结果仍然相同。请告诉我怎么做。

2 个答案:

答案 0 :(得分:1)

这可能会对你有所帮助。我已经更改了代码以使其变得简单。

$(document).ready(function () {
    $.getJSON("/Post/GetPosts", null, function (data) {

       //make parent div blank
        $(".div1").html("");

        $.each(data, function (i, item) {
        //make html for div2
        var html += "<div class='div2'>";
            html += item.PostedByName;
            html += "<img src='" + item.PostedByAvatar + "'height='100' width='100'/>"
            html += "</div>";

            //append all div2 to parent div1
            $(".div1").append(html);
        });

    });
});

答案 1 :(得分:0)

      $(document).ready(function () {
          $.getJSON("/Post/GetPosts", null, function(data)
          {
           htmlResultData="<br /> " + "Users received from server: " + "<br />";
           $.each(data, function (i, item)
           {
          htmlResultData +="<div class='div2'> item.PostedByName + "<img src='" + item.PostedByAvatar + "'height='100' width='100'/></div> ";
           });
            $(".div1").empty().append(htmlResultData);
        //however, i have tried to return false here but still same result
           //return false;
         });
       });