如何在jQuery中缓存DOM变量



演示

使用jquery和highchart.js(+exporting.js模块),我试图通过一个自定义按钮导出图表,如下面的

<button type="button" id="chartpdf" data-chart="chart1" class="pdf-download">PDF</button>

当代码以类似的硬编码格式导出图表时

chart1.exportChart({type: "application/pdf"});

当试图从元素数据属性data-chart="chart1" 中动态获取chart1时,它不起作用

$(document).on("click", ".pdf-download", function(){
     $(this).data('chart').exportChart({type: "application/pdf"});
});

你能告诉我怎么修吗?

感谢

试试这个

$( CHART ID ).highcharts().exportChart({type: "application/pdf"});

Example

我没有使用highchart.js,也不知道它是如何处理图表的。但在你的点击收听

$(this).data('chart');

应该返回一个字符串"chart1"(这里的if.data()充当jQuery的默认方法)你所做的等于

('chart1').exportChart({type: "application/pdf"});

switch与不同

chart1.exportChart({type: "application/pdf"});

我想得到"chart1"字符串后应该做些什么这意味着您应该将此字符串转换为您的chart1对象。

如果有什么我需要知道的(也许是关于highchart.js),请告诉我。

编辑:

根据@Alexander的回答,你可以这样做:

$(document).on("click", ".pdf-download", function(){
     var id = $(this).data('chart')
     $("#"+id).highcharts().exportChart({type: "application/pdf"});
});

据我所知,您想要读取对象chart1

有两种选择。

  1. 使用对象的id
  2. 如果只需要使用代码,则需要进行以下修改

更改此项:

$(function () {
    var chart1 = new Highcharts.Chart({

到此:

var chart1;
$(function () {
    chart1 = new Highcharts.Chart({

事件处理程序

$(document).on("click", ".pdf-download", function(){
    window[$(this).attr('data-chart')].exportChart({type: "application/pdf"});
});

希望这能有所帮助。

最新更新