如何在div中放置一个按钮,通过$ .each函数动态填充数据

时间:2015-12-30 08:24:09

标签: javascript jquery html

这应该很简单,但我在这里挣扎。

我有一个父div,它有多个子div。这些子div是根据$ .each()函数生成的。函数运行的次数,div生成的数量。现在,我想在按钮单击时编写服务器端函数,但我无法在这些子div中列出该按钮。

<div class="div1">
  <div class="div2">
    // this is the button which i cant see in my div2 div
    <button type="input">follow</button>
    <script type="text/javascript">
      $(document).ready(function() {
        $.getJSON("/Home/GetUsers", null, function(data) {
          $(".div1").html("");
          $.each(data, function(i, item) {

            var html = "<div class='div2'>";
            html += "Name: " + item.UserName + "<br />";
            html += item.ArticleCount;
            html += "<img src='" + item.UserImage + "'height='20px' width='20px'/>"
            html += "</div>";
            $(".div1").append(html);
          });
        });
      });
    </script>
  </div>
</div>

任何类型的指导表示赞赏。

1 个答案:

答案 0 :(得分:1)

如果你想为每个孩子div添加一个按钮,你可以这样做:

 $(document).ready(function() {
    var parent = $(".div1");

    $.getJSON("/Home/GetUsers", null, function(data) {

      parent.html("");

      $.each(data, function(i, item) {

        var html = "<div class='div2'>";
        html += "Name: " + item.UserName + "<br />";
        html += item.ArticleCount;
        html += "<img src='" + item.UserImage + "'height='20px' width='20px'/>";
        html += "<button type='button' class='newButton'>Click Me!</button>";
        html += "</div>";

        parent.append(html);
      });

    });

    // In order to ensure that the button click is handled no matter when it was 
    // added, we can delegate the handler to the parent.

    parent.on('click', '.newButton', function(e) {
       var button = $(this);

       // Handle the individual button click server side call here.
    });
  });
相关问题