简而言之,我使用 AJAX 调用从数组中检索值。绿色到红色背景将根据数字“aht_value”显示。颜色显示正确,因为我手动将值放入下面的计算中。也就是说,在我的“函数 conv(x)”中,我希望这些值是动态的。
有 3 件事我想在我的代码中实现但无法实现。所以,这是我的 fiddle for better understanding
- 从“aht_value”中的数组中获取最小值和最大值。供以后在 conv(x) 函数中使用。
- 如果 aht_value 等于“NA”,则显示白色背景。
- 使值不超过小方 block ..我怎样才能使它们居中以使数字不重叠?
这是从我的“show_aht.php”中检索的数组示例。
数组:
[
{
"username":"OXGOR",
"aht_value":"241",
"station":"B20"
}
{
"username":"AISAI2",
"aht_value":"199",
"station":"B21"
},
{
"username":"CAPAP3",
"aht_value":"NA",
"station":"B10"
}
]
AJAX 调用:
<script type="text/javascript">
$(document).ready(function() {
$('#aht').click(function(){
$.ajax({
type:"GET",
url : "show_aht.php",
data:{ } , // do I need to pass data if im GET ting?
dataType: 'json',
success : function(data){
//going through all DIVs only once with this loop
for(var i = 0; i < data.length; i++) { // loop over results
var divForResult = $('#desk_' + data[i]['station']); // look for div for this object
if(divForResult.length) { // if a div was found
这里我输出的是背景色和aht_value
divForResult.html(data[i]['aht_value']).css("background-color", colorMe(data[i]['aht_value']));
}//end if
}//end for
}//end success
});//end ajax
});//end click
});//end rdy
//function for background color
function colorMe(v){
return "rgb(" + conv(v) + "," + (255-conv(v)) + ",0)";
}
这里我想检查数组中的最低值和最高值以进行计算 我添加了 1800 作为最高值,100 作为最低值,但我希望它是数组中的值
//function for calculation of background color depending on aht value
function conv(x){
return Math.floor((x - 100) / (1800-100) * 255);
}
</script>
最佳答案
您的 json 文件无效。 Ajax 调用使用严格的方法,因此如果 json 无效,它将不会到达您的成功函数。
首先尝试在此处调试 json 文件:http://jsonlint.com/
尝试使用这个 json(固定):
[
{
"username": "OXGOR",
"aht_value": "241",
"station": "B20"
},
{
"username": "AISAI2",
"aht_value": "199",
"station": "B21"
},
{
"username": "CAPAP3",
"aht_value": "NA",
"station": "B10"
}
]
关于javascript - 根据 MIN 和 MAX 数组值更改 DIV 颜色背景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27026074/