如何使用jquery在旋钮图上显示值?

时间:2020-02-14 11:06:11

标签: jquery html ajax bootstrap-4 jquery-knob

  1. 如何使用Bootstrap 4中的jQuery Knob Chart显示来自某些URL的值。我得到了“ NaN”值。 (请参考下面的代码)
  2. 如果数据为空,如何显示“-”破折号。 (请参考下面的代码)

enter image description here

HTML

<input type="text" class="knob" id="avg_temperature" data-width="120" data-height="120" data-thickness="0.40" data-fgColor="#000000" readonly>

JS

$.ajax({
    url : XXX,
    type : 'POST',
    dataType : 'json',
    cache: false,
    async: false,
    dataSrc : 'data',
    contentType: false,
    processData: true,
    success: function(response){
        if (response.status == "Success"){            
            if (response.data[0]["avg_temperature"] == null){
                response.data[0]["avg_temperature"] = "-";
                $("#avg_temperature").text("-");
            }
            $("#avg_temperature").text(response.data[0]["avg_temperature"]);

            var colors = ['#11E117', '#FFC300', '#C00']

            //knob chart for temperature
            $('#avg_temperature').knob();
            $('#avg_temperature').attr('data-fgColor', '#11E117');

            $({animatedVal: 0}).animate({animatedVal: response},{
                duration: 3000,
                easing: "swing",
                async: false,
                step: function() {
                    var val = Math.ceil(this.animatedVal);
                    $("#avg_temperature").trigger('configure', {
                        'fgColor': colors[(val < 40) ? 0 : (val < 70) ? 1 : 2]
                    }).val(val).trigger("change");
                    var newVal = val + String.fromCharCode(176) + 'C'; $('#avg_temperature').val(newVal);
                }
            });
        }
    },
});

1 个答案:

答案 0 :(得分:1)

从代码的上下文来看,response似乎是一个对象,这是问题的原因,因为animate()期望您提供的值是整数。

从您在代码中其他地方使用response的上下文来看,您似乎需要从中访问特定的temperature属性,如下所示:

if (response.data[0]["avg_temperature"] == null)
    response.data[0]["avg_temperature"] = "-";

var colors = ['#11E117', '#FFC300', '#C00']

let $avgTemp = $("#avg_temperature").text(response.data[0]["avg_temperature"]);
$avgTemp.data('fgColor', '#11E117').knob();

$({
  animatedVal: 0
}).animate({
  animatedVal: parseInt(response.data[0]["avg_temperature"], 10) // update here
}, {
  duration: 3000,
  easing: "swing",
  step: function() {
    var val = Math.ceil(this.animatedVal);
    $avgTemp.trigger('configure', {
      'fgColor': colors[(val < 40) ? 0 : (val < 70) ? 1 : 2]
    }).val(val).trigger("change");

    var newVal = val + String.fromCharCode(176) + 'C';
    $avgTemp.val(newVal);
  }
});

还要注意删除了async: false。这是不好的做法,而且您在这里也不需要它

相关问题