0

我正在使用 Highcharts 并以 JSON 格式从服务器发送 plotBands 的 xAxis 选项。我正在尝试在 plotband 中添加 click 方法。如果我在 HTML 文件中对其进行硬编码,一切正常,但是当我从服务器发送动态生成的代码时,它会显示 plotband 但单击不起作用。我已经获取了 JSON 输出并将其直接放入 HTML 文件中,它在那里工作

我的 JSON 输出:

[{"from":1349067600000,"to":1349758800000,"color":"rgba(68, 170, 213, .2)","events":{"click":"function(e) {alert(999);}"}},{"from":1350018000000,"to":1350622800000,"color":"rgba(68, 170, 213, .2)","events":{"click":"function(e) {alert(999);}"}}]

有效的代码:

            plotBands:[ {from:Date.UTC(2012,09,01),to:Date.UTC(2012,09,05),color:'rgba(68, 170, 213, .2)',events:{click:function(e) {alert(999);}}},
                        {from:Date.UTC(2012,09,07),to:Date.UTC(2012,09,12),color:'rgba(68, 170, 213, .2)',events:{click:function(e) {alert(999);}}}
                    ],

从 PHP 生成 JSON 的代码:

$treatmentsList[$counter]=array('from'=>strtotime($PatPresVal->pres_med_start_date)*1000,'to'=>strtotime($PatPresVal->pres_med_end_date)*1000, 'color'=>'rgba(68, 170, 213, .2)','events'=>array('click'=>'function(e) {alert(999);}'));

我确信这是一件小事,但我几个小时都找不到它……在此先感谢。

4

1 回答 1

1

JSON 通常不支持返回函数,尤其是不像你所做的那样将函数作为字符串返回:

"events":{"click":"function(e) {alert(999);}"}}

您可能会强制它使用 aneval但我不鼓励这样做。

更好的选择是在收到 JSON 响应后循环 plotBands 对象并添加事件处理程序:

for (var i = 0; i < plotBands.length; i++)
{
    plotBands[i]['events'] = {};
    plotBands[i]['events']['click'] = function(e) {alert(999);}
}
于 2013-06-29T15:43:29.030 回答