gpt4 book ai didi

javascript - 设置innerHTML 的函数调用不起作用 - 给出未定义

转载 作者:行者123 更新时间:2023-11-28 19:43:18 25 4
gpt4 key购买 nike

我正在尝试通过调用的 Javascript 函数动态设置 div 元素的innerHTML。当调用该函数并正确打印调试消息时,innerHTML 为“未定义”。我不明白为什么 - 任何帮助将不胜感激。

这是我写的:

    <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>

非常感谢您的帮助。

最佳答案

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 错误。回调允许函数运行,当函数完成时,它将运行您传入的函数。

关于javascript - 设置innerHTML 的函数调用不起作用 - 给出未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24689051/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com