设置innerHTML的函数调用不起作用 - 给出Undefined

时间:2014-07-11 01:57:52

标签: javascript jquery html

我试图通过一个被调用的Javascript函数动态地为div元素设置innerHTML。在调用函数并正确打印调试消息时,innerHTML是“Undefined”。我无法弄清楚为什么 - 非常感谢你的帮助。

这是我写的:

    <script type="text/javascript">
  var clientsHealthStat = function (color) { // color is the RED / YELLOW / GREEN status of the client
    var ClientPerfsREST = 'http:/localhost:8081/c3rests/c3/ClientPerfs';
    var ClientCntr = 0; // provide the count of clients for the specific status
    $.getJSON(ClientPerfsREST, function(ClientPerfsJson){
      $.each(ClientPerfsJson.payload.array,function(i,performance){
        if (performance.attributes.Status === color) { ClientCntr++; }
      }); // End of loop through result set
      return ClientCntr; // return the client count with Health Color
    }); // End of getJSON(SummaryPerfsREST, function())
  }
</script>
    <script type="text/javascript">
  $(document).ready(function(){
    var parentElement = document.getElementById('customerHealthSummary');
    var healthStatusIndicators = ['red','yellow','green'];
    for (var i = 0; i < healthStatusIndicators.length; i++) {
      var childElement = document.createElement('div');
      childElement.style.width = '100%';
      childElement.style.backgroundColor = healthStatusIndicators[i];
      childElement.title = healthStatusIndicators[i].toUpperCase();
      console.log(clientsHealthStat(healthStatusIndicators[i].toUpperCase()));
      childElement.innerHTML = clientsHealthStat(healthStatusIndicators[i].toUpperCase());
      parentElement.appendChild(childElement);
    };
  }); // End of document ready function
</script>

非常感谢你的帮助。

1 个答案:

答案 0 :(得分:3)

clientsHealthStat是异步函数(嗯,getJSON调用是异步的) - 您需要使用回调:

var clientsHealthStat = function (color, callback) { // color is the RED / YELLOW / GREEN status of the client
    var ClientPerfsREST = 'http:/localhost:8081/c3rests/c3/ClientPerfs';
    var ClientCntr = 0; // provide the count of clients for the specific status
    $.getJSON(ClientPerfsREST, function(ClientPerfsJson){
        $.each(ClientPerfsJson.payload.array,function(i,performance){
            if (performance.attributes.Status === color) { ClientCntr++; }
        }); // End of loop through result set
        callback(ClientCntr);
    }); // End of getJSON(SummaryPerfsREST, function())
}

然后调用函数:

clientsHealthStat(healthStatusIndicators[i].toUpperCase(), function(data) {
    childElement.innerHTML = data;
});

在您的代码中,您调用了该函数并尝试在getJSON调用完成之前返回,因此您收到undefined错误的原因。回调允许函数运行,当它完成时,它将运行您传入的函数。