为什么索引从不== 0?

时间:2016-02-04 15:28:32

标签: javascript jquery html

      <script>
        var index = 0;
        $.getJSON("./data/data.json", function(json) {
          $.each(json, function(data) {
            var html = "";                
            if(index == 0)
            {
              console.log(index + " first item");
              html = "<div class='item active'>";
            } else {
              console.log(index + " its not 0");
              html = "<div class='item'>"
            }
            console.log(json.length); // this will show the info it in firebug console
            html += "<blockquote><div class='row'><div class='col-sm-3 text-center'><img class='img-circle' src='images/obama.jpg' style='width: 100px;height:100px;'></div><div class='col-sm-9'><p>Change will not come if we wait for some other person or some other time. We are the ones we've been waiting for. We are the change that we seek.</p><small>President Barack Obama</small></div></div></blockquote></div>";
            $('body').append(html);
            index++;
          });
        });
      </script>

我需要生成其中的5个,但第一个需要'项目有效'

如果有更好的方法,请告诉我

感谢您指出我的html被覆盖了。我更新了我的代码,但jQuery实际上并没有把我的HTML放到正文中。那就是另一个问题

2 个答案:

答案 0 :(得分:4)

您可以在$.each方法中添加索引;这将从0到data.length - 1

$.getJSON("./data/data.json", function(json) {
  $.each(json, function(index, data) {
    var html = "";
    html += '<div class="item' + (index == 0 ? ' active' : '') + '">';
    html += '<blockquote>...</blockquote>';
    html += '</div>';
    $('body').append(html);
  });
});

答案 1 :(得分:2)

<script>
    var index = 0;
    $.getJSON("./data/data.json", function(json) {
      $.each(json, function(data) {
        var html = "";

        if(index == 0)
            html = "<div class='item active'>";
        else
            html = "<div class='item'>";

        html += "<blockquote><div class='row'><div class='col-sm-3 text-center'><img class='img-circle' src='images/obama.jpg' style='width: 100px;height:100px;'></div><div class='col-sm-9'><p>Change will not come if we wait for some other person or some other time. We are the ones we've been waiting for. We are the change that we seek.</p><small>President Barack Obama</small></div></div></blockquote></div>";

        $('body').append(html);
      index++;
      });
    });
</script>