Javascript 为什么索引从不==0?

Javascript 为什么索引从不==0?,javascript,jquery,html,Javascript,Jquery,Html,我需要生成其中5个,但第一个需要是“项目活动” 如果有更好的办法,请告诉我 谢谢你指出我的html被覆盖了。我更新了我的代码,但jQuery实际上并没有将我的HTML放入正文中。所以这是另一个问题您可以在方法中添加索引;这将从0扩展到data.length-1 <script> var index = 0; $.getJSON("./data/data.json", function(json) { $.each(jso

我需要生成其中5个,但第一个需要是“项目活动”

如果有更好的办法,请告诉我
谢谢你指出我的html被覆盖了。我更新了我的代码,但jQuery实际上并没有将我的HTML放入正文中。所以这是另一个问题

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

      <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>
$.getJSON./data/data.json,functionjson{ $.eachjson,函数索引,数据{ var html=; html+=; html+='…'; html+=; $'body'.html; };
};考虑到这些代码,我看不出为什么索引不总是0。你总是覆盖html,使你的if语句变得多余。你从不更改索引,所以它总是为零…你的日志上说索引是什么?@SoftwareSFun它总是运行if代码,但是你的代码仍然会在if块之后立即覆盖html的值。我正要在同一个问题上点击publish+1,对于OP:这里有一个指向$的链接。每个api:不需要单独的计数器-看看@ChrisForrenceanswer@Christer完全忽略了它在jquery中的事实,哈哈。
<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>