根据循环中变量的值更改img src

时间:2018-04-20 19:04:55

标签: javascript jquery arrays for-loop

我使用jquery getJSON函数从JSON文件调用内容,它返回一个名为items的集合,并有两个值:

  1. 1到10之间的整数值
  2. 一些文字
  3. 然后在jquery每个循环中我运行数组项并基于整数值尝试定位图像标记以更改其源,但它不起作用。

    此外,我在页面上使用Bootstrap来显示转盘中的文本内容,它正常工作。添加下面的代码。根据我的测试,似乎当检查放在每个jquery中时,系统一次运行整个循环,最后一个迭代条件应用于div。

    有人可以帮忙解决如何阻止这种情况发生的事吗?

    $.getJSON("/samplecsat.json", function(result) {
      myarr = result.items;
      console.log("result is: " + JSON.stringify(result.items));
      console.log("total count is: " + result.items.length);
      total = result.items.length;
      $.each(myarr, function(i, field) {
        x = field["Survey Rating"];
        if (i == 0) {
          console.log("YAY its the first iteration" + i);
          if (x < 8) {
            dsat = dsat + 1;
            $('<div class="item active" style="color:red"><em>' + field["Customer Verbatim"] + '</em></div>').appendTo('.carousel-inner');
            $("#myCarousel").on('slide.bs.carousel', function() {
              $("#customersentiment").attr("src", "/csp/angry.gif");
            });
          } else {
            sat = sat + 1;
            $('<div class="item active" style="color:green">' + field["Customer Verbatim"] + '   </div>').appendTo('.carousel-inner');
            console.log("it is a csat with rating:" + " " + field["Survey Rating"])
            $("#myCarousel").on('slide.bs.carousel', function() {
              $("#customersentiment").attr("src", "/csp/happy.gif");
            });
    
          }
        } else {
          if (x < 8) {
            dsat = dsat + 1;
            $("#customersentiment").attr("src", "/csp/angry.gif");
            $('<div class="item" style="color:red"><em>' + field["Customer Verbatim"] + '</em></div>').appendTo('.carousel-inner');
            console.log(" its a dsat with rating:" + " " + field["Survey Rating"]);
            $("#myCarousel").on('slide.bs.carousel', function() {
              $("#customersentiment").attr("src", "/csp/angry.gif");
            });
          } else {
            sat = sat + 1;
            $("#customersentiment").attr("src", "");
            $('<div class="item" style="color:green"><em>' + field["Customer Verbatim"] + '</em></div>').appendTo('.carousel-inner');
            console.log("it is a csat with rating:" + " " + field["Survey Rating"])
            $("#myCarousel").on('slide.bs.carousel', function() {
              $("#customersentiment").attr("src", "/csp/happy.gif");
            });
          }
        }
      })
      console.log("Total DSATs by Js: " + dsat);
      console.log("Total CSATs by Js: " + sat);
      console.log("Total item count is: " + total);
      satpercentage = (sat * total / 100) * 100 + "%";
      console.log("percentage is: " + sat * total / 100);
      console.log("total is second one:" + total);
    });
    

0 个答案:

没有答案