经过对 stackoverflow 的详尽研究,我没有找到任何解决我的问题的方法,我不得不打开一个新线程。 我有一个基于 highcharts 的图表,使用 json 文件。不过,我有 3 个不同的 json 文件,我希望通过单击即可更改它们。 简而言之:当单击按钮“day”时,我想要 $getJSON 文件“./json/historyday.json”。当我点击月份时,我想要 $getJSON 文件“./json/historymonth.json”。 请在下面找到我的代码:
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<script src="https://code.highcharts.com/stock/modules/export-data.js"></script>
<input type="button" id="hour" value="hour" />
<input type="button" id="day" value="day" />
<div id="container" style="height: 400px; max-width: 900px"></div>
<script>
// file change with click
var filejson = './json/historyday.json';
$('#hour').click(function (){
var filejson = '../json/historyday.json';
});
$('#day').click(function (){
var filejson = '../json/historymonth.json';
});
$.getJSON(filejson, function (data) {
var currentValue = (data[data.length - 1][1]);
Highcharts.stockChart('container', {
rangeSelector: {
enabled: false
},
title: {
text: 'AAPL Stock Price'
},
yAxis: {
title: {
text: 'Exchange rate'
},
plotLines: [{
value: currentValue,
color: 'green',
dashStyle: 'solid',
width: 2,
label: {
text: currentValue + 'EUR'
}
}]
},
series: [{
name: 'AAPL Stock Price',
data: data,
type: 'areaspline',
threshold: null,
tooltip: {
valueDecimals: 2
},
fillColor: {
linearGradient: {
x1: 0,
y1: 0,
x2: 0,
y2: 1
},
stops: [
[0, Highcharts.getOptions().colors[0]],
[1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
]
}
}]
});
});
</script>
最佳答案
将您的代码包装在一个函数中,您可以将要加载的 JSON 数据的文件名传递给该函数。然后,您可以使用每个按钮的点击处理程序中不同的文件名调用该函数:
var drawChart = function(filejson) {
console.log("Get data for ", filejson);
$.getJSON(filejson, function(data) {
// ... your code to draw the chart here
});
}
$('#day').on("click", function() {
drawChart("./json/historyday.json");
});
$('#month').on("click", function() {
drawChart("./json/historymonth.json");
});
$('#hour').on("click", function() {
drawChart("./json/historyhour.json");
});
// Draw one of them by default:
drawChart("./json/historyday.json");
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<input type="button" id="month" value="month" />
<input type="button" id="day" value="day" />
<input type="button" id="hour" value="hour" />
<div id="container" style="height: 400px; max-width: 900px"></div>
您当前在这些点击处理程序中尝试执行的操作(至少在对问题的最新编辑中)只是更改 filejson
变量的内容;这不会做任何可见的事情,因为 ajax 调用和实际绘制图表仍然需要被触发。
关于javascript - 单击 jquery 更改变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50974931/