【问题标题】:AJAX/jQuery: Change DIV background based on number value in it?AJAX/jQuery:根据其中的数值更改 DIV 背景?
【发布时间】:2014-11-20 01:14:51
【问题描述】:

我是 AJAX/jQuery 的新手,正在尝试新的东西。

here is my fiddle for better understanding每个方块都是DIVS。

<div class="desk_box_ver" id="desk_B20" data-rel="85" style="left:20px;top:1165px;">B20</div>

内部的数字是通过 AJAX 调用检索的,该调用通过执行 PHP 脚本获取它 一个查询,它将以“1300”替换“B20”作为示例。

问题:

如何根据显示的数字生成“热图”。 示例:假设数字范围是从 100(最低)到 1800(最高)。 根据数字范围,必须显示背景颜色 绿色、黄色、橙色和红色。

我在stackoverflow上发现的一个类似问题是this one

AJAX:我如何在 DIV 中显示数字

<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

这是我输出数字的地方

      divForResult.html(data[i]['aht_value']); // set inner HTML with AHT value


                            }//end if
                            }//end for
                      }//end success
                });//end ajax
              });//end click
            });//end rdy
        </script>

正在从下面的数组中检索到的 show_aht.php 数字

$result = array();
    foreach ($memo as $username => $memodata) {
    if (in_array($username, array_keys($user))) {
    // Match username against the keys of $user (the usernames) 
    $userdata = $user[$username];
    //if AHT is null give N/A as value
    if (is_null($memodata['aht_value'])) {
        $result[] = array( 'username'  => $userdata['username'],
                                             'aht_value' => 'NA',
                                             'station'  => $userdata['station']
                                            );
    }//end inner if 
    //else give the actual value of AHT without the decimals
    else {
        $result[] = array( 'username'  => $userdata['username'],
                                             'aht_value' => substr($memodata['aht_value'],0,-3),
                                             'station'   => $userdata['station']
                                            );
    }//end else
    }//end outer if
    }//end for

echo json_encode($result);

【问题讨论】:

  • 你的小提琴好像有问题
  • @SimonH 有什么问题?

标签: javascript php jquery css ajax


【解决方案1】:

this fiddle一起玩。它插入一个值,然后将颜色应用于 is(使用您想要更改的非常简单的算法)。以下是如何在代码中实现它

success : function(data){
  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
       divForResult.html(data[i]['aht_value']).css("background-color", colorMe(data[i]['aht_value']));
    }//end if
  }//end for
}//end success

使这些在您的代码中可用:

function colorMe(v){
    return "rgb(" + conv(v) + "," + (255-conv(v)) + ",0)";
}

function conv(x){
    return Math.floor((x - 100) / (1800-100) * 255);
}

【讨论】:

  • 这会给它随机的颜色。我想要的是从绿色一直到红色。我该怎么做?谢谢
  • 我们继续聊天你介意吗?我真的很想知道如何将您的解决方案合并到我的代码中。颜色变化的方式正是我想要的。谢谢
  • 非常感谢!真的行!你介意解释我如何设置我的最低和最高价值吗?谢谢!
  • 进行了小幅编辑,以展示我如何将 100 和 1800 合并到 conv 中
  • 太棒了,非常感谢您的帮助!正在用硬代码绕圈子。你的代码既简单又聪明!
【解决方案2】:

我不确定我是否完全理解了这个问题,但这是最简单的想法,希望能帮到你:http://jsfiddle.net/Arministrator/0vhv37jf/

$( document ).ready(function() {

    var valuediv = document.getElementById('valuediv');
    var valuedive = valuediv.innerHTML;
    $("#valuediv").css({"background-color":"#"+valuedive});
});

div 中的任何数字都会影响 div 的颜色。如果您想要超过 3 位数字,您可以使用它,这只是一个指导您的示例。 (例如#900 是红色)

【讨论】:

    【解决方案3】:

    我编写了一个通用函数,它接受一个数字和一个范围对象作为参数,并根据数字在范围内的位置计算数字的颜色。

    /**
     * Calculate a color based on number's position in a range.
     * @param  {number} num  Number to calculate a color for
     * @param  {object} opts Range of colors and numbers in the following form:
     *                       {
     *                          start: {number: {number}, color: {rgb array: [r,g,b]}},
     *                          end:   {number: {number}, color: {rgb array: [r,g,b]}}
     *                       }
     *                       where each of "r", "g", "b" is a value from 0 to 255.
     *                       I.e. a range specifying numbers from 0 to 100 with colors from black to white: {start: {number: 0, color: [0,0,0]}, end: {number: 100, color: [255,255,255]}}
     * @return {string}      CSS color
     */
    function colorCode(num, opts) {
        var color = [];
    
        if(num <= opts.start.number)
            color = opts.start.color;
        else if(num >= opts.end.number)
            color = opts.end.color;
        else {
            for(var i = 0; i < 3; i++) {
                color[i] = Math.round( (num - opts.start.number) / (opts.end.number - opts.start.number) * (opts.end.color[i] - opts.start.color[i]) + opts.start.color[i] );
            }
        }
    
        return 'rgb(' + color.join() + ')';
    }
    

    fiddle

    【讨论】:

    • 不错的代码,所以如果我想在 IF 语句中调用函数 colorCode 我会这样称呼它吗? divForResult.html(data[i]['aht_value']).css("background-color", colorCode(data[i]['aht_value'],data[i]['aht_value'] )); 因为参数是数值的两倍?如果我理解正确。谢谢
    • 不完全是,@alda1234。 "colorCode" 接受一个数字作为第一个参数(你是对的),但第二个参数必须是一个对象。请参阅函数前的 jsdoc 说明。我还在那里包含了一个示例用法。
    猜你喜欢
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-22
    • 2013-12-09
    • 1970-01-01
    相关资源
    最近更新 更多