繁体   English   中英

来自 ajax 插入数据的 Highcharts 迷你图

[英]Highcharts sparklines from ajax-inserted data

您有一个 html 表格,并且想要根据您的数据显示迷你图,与本示例完全相同(来自 highcharts 演示):

https://codepen.io/_dario/pen/rNBOGVR

Highcharts 建议的代码如下:

/**
 * Create a constructor for sparklines that takes some sensible defaults and merges in the individual
 * chart options. This function is also available from the jQuery plugin as $(element).highcharts('SparkLine').
 */
Highcharts.SparkLine = function(a, b, c) {
  var hasRenderToArg = typeof a === 'string' || a.nodeName,
    options = arguments[hasRenderToArg ? 1 : 0],
    defaultOptions = {
      chart: {
        renderTo: (options.chart && options.chart.renderTo) || this,
        backgroundColor: null,
        borderWidth: 0,
        type: 'area',
        margin: [2, 0, 2, 0],
        width: 120,
        height: 20,
        style: {
          overflow: 'visible'
        },

        // small optimalization, saves 1-2 ms each sparkline
        skipClone: true
      },
      title: {
        text: ''
      },
      credits: {
        enabled: false
      },
      xAxis: {
        labels: {
          enabled: false
        },
        title: {
          text: null
        },
        startOnTick: false,
        endOnTick: false,
        tickPositions: []
      },
      yAxis: {
        endOnTick: false,
        startOnTick: false,
        labels: {
          enabled: false
        },
        title: {
          text: null
        },
        tickPositions: [0]
      },
      legend: {
        enabled: false
      },
      tooltip: {
        hideDelay: 0,
        outside: true,
        shared: true
      },
      plotOptions: {
        series: {
          animation: false,
          lineWidth: 1,
          shadow: false,
          states: {
            hover: {
              lineWidth: 1
            }
          },
          marker: {
            radius: 1,
            states: {
              hover: {
                radius: 2
              }
            }
          },
          fillOpacity: 0.25
        },
        column: {
          negativeColor: '#910000',
          borderColor: 'silver'
        }
      }
    };

  options = Highcharts.merge(defaultOptions, options);

  return hasRenderToArg ?
    new Highcharts.Chart(a, options, c) :
    new Highcharts.Chart(options, b);
};

var start = +new Date(),
  $tds = $('td[data-sparkline]'),
  fullLen = $tds.length,
  n = 0;

// Creating 153 sparkline charts is quite fast in modern browsers, but IE8 and mobile
// can take some seconds, so we split the input into chunks and apply them in timeouts
// in order avoid locking up the browser process and allow interaction.
function doChunk() {
  var time = +new Date(),
    i,
    len = $tds.length,
    $td,
    stringdata,
    arr,
    data,
    chart;

  for (i = 0; i < len; i += 1) {
    $td = $($tds[i]);
    stringdata = $td.data('sparkline');
    arr = stringdata.split('; ');
    data = $.map(arr[0].split(', '), parseFloat);
    chart = {};

    if (arr[1]) {
      chart.type = arr[1];
    }
    $td.highcharts('SparkLine', {
      series: [{
        data: data,
        pointStart: 1
      }],
      tooltip: {
        headerFormat: '<span style="font-size: 10px">' + $td.parent().find('th').html() + ', Q{point.x}:</span><br/>',
        pointFormat: '<b>{point.y}.000</b> USD'
      },
      chart: chart
    });

    n += 1;

    // If the process takes too much time, run a timeout to allow interaction with the browser
    if (new Date() - time > 500) {
      $tds.splice(0, i + 1);
      setTimeout(doChunk, 0);
      break;
    }

    // Print a feedback on the performance
    if (n === fullLen) {
      $('#result').html('Generated ' + fullLen + ' sparklines in ' + (new Date() - start) + ' ms');
    }
  }
}
doChunk();

但是,在我的用例中,表中的数据(和data-sparkline属性)不像示例中那样进行硬编码,而是通过 AJAX 调用加载和显示,类似于下面的内容。

//here a table row gets compiled
var tableRow = '<tr id="row_' + word.id + '">';

//this is where the sparkline data go
tableRow += '<td class="has-sparkline"></td></tr>';

//the row gets appended to tbody
$('#wordstable tbody').append(tableRow);

//finally the sparkline data are attached
//data are a simple string such as "1,2,3,4,5"

var rowId = '#row_'+word.id;
var rowIdTd = rowId + ' td.has-sparkline';
$(rowIdTd).data('sparkline',word.sparkline);

这打破了示例逻辑,我不能让 Highcharts“看到”数据。

没有返回特定的错误(就 Highcharts 而言,就数据而言,只是不存在,因此无事可做)。

doChunk位只是提前完成所有处理,当您添加行时,它不再处理。 处理此问题的一种方法是将创建单个图表的部分提取到单独的函数 ( makeChart ) 中,并在进行处理时直接使用该部分来创建makeChart图。

例如, doChunk具有分裂出来makeChart

function makeChart(td) {
    $td = td;
    stringdata = $td.data('sparkline');
    arr = stringdata.split('; ');
    data = $.map(arr[0].split(', '), parseFloat);
    chart = {};

    if (arr[1]) {
      chart.type = arr[1];
    }
    $td.highcharts('SparkLine', {
      series: [{
        data: data,
        pointStart: 1
      }],
      tooltip: {
        headerFormat: '<span style="font-size: 10px">' + $td.parent().find('th').html() + ', Q{point.x}:</span><br/>',
        pointFormat: '<b>{point.y}.000</b> USD'
      },
      chart: chart
    });

}

// Creating 153 sparkline charts is quite fast in modern browsers, but IE8 and mobile
// can take some seconds, so we split the input into chunks and apply them in timeouts
// in order avoid locking up the browser process and allow interaction.
function doChunk() {
  var time = +new Date(),
    i,
    len = $tds.length,
    $td,
    stringdata,
    arr,
    data,
    chart;

  for (i = 0; i < len; i += 1) {
    makeChart($($tds[i]));

    n += 1;

    // If the process takes too much time, run a timeout to allow interaction with the browser
    if (new Date() - time > 500) {
      $tds.splice(0, i + 1);
      setTimeout(doChunk, 0);
      break;
    }

    // Print a feedback on the performance
    if (n === fullLen) {
      $('#result').html('Generated ' + fullLen + ' sparklines in ' + (new Date() - start) + ' ms');
    }
  }
}

然后是 ajax 代码的基本示例:

function ajaxIsh() {
    var word = {
    name: 'Bird', // is the word
    id: 'bird',
    sparkline: '1, 2, 3, 4, 5'
  };

  //here a table row gets compiled
  var tableRow = '<tr id="row_' + word.id + '">';

  //this is where the sparkline data go
  tableRow += '<th>'+word.name+'</th><td class="has-sparkline"></td></tr>';

  //the row gets appended to tbody
  $('#table-sparkline tbody').append(tableRow);

  //finally the sparkline data are attached
  //data are a simple string such as "1,2,3,4,5"

  var rowId = '#row_'+word.id;
  var rowIdTd = rowId + ' td.has-sparkline';
  $(rowIdTd).data('sparkline',word.sparkline);

  makeChart($(rowIdTd));
}

请参阅此 JSFiddle 的实际演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM