我正在尝试将localstorage值添加到highchart系列中,但它不起作用。
当我在控制台上打印“newString”值并在其运行的代码中替换“newString”的值时,但在我使用var newString
时则不会。
以下是代码:
$(document).ready(function () {
var archive,
j = "",
keys = Object.keys(localStorage),
x = keys.length;
var i = 0;
while (i < x) {
archive = JSON.parse(localStorage.getItem(keys[i]));
j += "{ name: " + keys[i] + ", data: [" + archive.username + ", " + archive.email + ", " + archive.password + "]},";
i++;
}
var newString = j.substr(0, j.length - 1);
console.log('newString: ', newString);
Highcharts.chart('container', {
title: {
text: 'Datos ingresados'
},
subtitle: {
text: 'Localstorage'
},
yAxis: {
title: {
text: 'Datos ingresados'
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle'
},
plotOptions: {
series: {
label: {
connectorAllowed: false
},
pointStart: 2017
}
},
series: [
newString
],
responsive: {
rules: [{
condition: {
maxWidth: 500
},
chartOptions: {
legend: {
layout: 'horizontal',
align: 'center',
verticalAlign: 'bottom'
}
}
}]
}
});
});
这就是console.log显示的内容:
{name:2,data:[12345,23458,34567]},{name:3,data:[23456,34567,45678]},{name:4,data:[34567,45678,56789]} ,{name:5,data:[45678,56789,67890]}
当我为此更改newString的值时,它可以正常工作。
答案 0 :(得分:0)
因为在第二种情况下,Highcharts
将您的数据视为纯字符串。所以,你需要解析你的字符串。
但首先,我们应该为正确解析创建有效的json:
var newString = "{ name: 2, data: [12345, 23456, 34567]}"; //bad json
var json = newString.replace(/(['"])?([a-zA-Z0-9]+)(['"])?:/g, '"$2":');
var goodJson = "[" + json + "]"; //valid json
现在我们可以为Highcharts
创建选项:
var options = {
chart: {
renderTo: 'container',
type: 'spline'
},
series: []
};
按如下方式将数据推送到series
:
$.each(JSON.parse(goodJson), function(i, item) {
options.series.push({
name: item.name,
data: item.data
});
});
最后初始化Highcharts
:
var chart = new Highcharts.Chart(options);
<强> See at Plunker 强>