可变颜色不会根据值更改

时间:2015-09-15 06:03:22

标签: jquery css json html5 xmlhttprequest

我正在尝试根据值为HTML变量指定颜色。该值从JSON中被选中,但颜色没有变化。

以下是调用变量并分配值的脚本:

<script>
  var xmlcurrgct = new XMLHttpRequest();
  var urlcurrgct = "../json/currgct.json";
  xmlcurrgct.onreadystatechange = function() {
    if (xmlcurrgct.readyState == 4 && xmlcurrgct.status == 200) {
      console.log("xmlcurrgct.responseText", xmlcurrgct.responseText);
      var obj1 = JSON.parse(xmlcurrgct.responseText);
      console.log("obj1", obj1);
      document.getElementById("currgct").innerHTML = obj1.text.currgct;
    }
  }
  xmlcurrgct.open("GET", urlcurrgct, true);


  var color;
  switch (currgct) {
    case "UP":
      color = "yellow";
      break;
    case "DOWN":
      color = "red";
      break;
  };
  xmlcurrgct.send();;
</script>

我不确定我缺少什么。变量可以有2个值 UP DOWN

JSON:
{"text":{"currgct":"UP"}}

有人可以帮我找到我错的地方吗?

1 个答案:

答案 0 :(得分:1)

试试这个:

var xmlcurrgct = new XMLHttpRequest();
var urlcurrgct = "../json/currgct.json";
xmlcurrgct.onreadystatechange = function () {
    if (xmlcurrgct.readyState == 4 && xmlcurrgct.status == 200) {
        console.log("xmlcurrgct.responseText", xmlcurrgct.responseText);
        var obj1 = JSON.parse(xmlcurrgct.responseText);
        console.log("obj1", obj1);
        document.getElementById("currgct").innerHTML = obj1.text.currgct;

        // You need to wait for the asynchronous response.
        var color;
        switch (obj1.text.currgct) {
            case "UP":
                color = "yellow";
                break;
            case "DOWN":
                color = "red";
                break;
        };

        document.getElementById("currgct").setAttribute("style", "color: " + color + ";");
    }
}
xmlcurrgct.open("GET", urlcurrgct, true);
xmlcurrgct.send();