我正在尝试根据选择特定的日期条件来呈现图表。当我从下拉列表中选择一个选项(例如每月)时,我希望图表能够呈现不同的数据集。
目前,下面的脚本没有执行上述预期输出(当我从选择列表中选择每日/每月时,它没有显示数据)。我在下面的代码中遗漏了什么?请指教。
这是我的代码:
var dataDaily = [
['CVR', 'TALK'],
[90, 353]
];
var dataWeekly = [
['CVR', 'TALK'],
[225, 893]
];
var dataMonthly = [
['CVR', 'TALK'],
[1602, 4934]
];
$(function () {
// Initial chart
var chart = c3.generate({
data: {
rows: dataDaily,
type: 'pie'
}
});
// Redraw chart depending on which option is selected
$("#DataType").change(function (evt) {
var timeSelection = $("#DataType").val();
var chart = c3.generate({
data: {
rows: timeSelection,
type: 'pie'
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.css">
<select id="DataType">
<option value="dataDaily">Daily</option>
<option value="dataWeekly">Weekly</option>
<option value="dataMonthly">Monthly</option>
</select>
<div id="chart"></div>
您还可以在此JSFiddle上看到代码(和问题)的演示:http://jsfiddle.net/km97cdL3/
答案 0 :(得分:4)
问题出在这一行:
var timeSelection = $("#DataType").val();
下拉列表的值是一个字符串(&#34; dataDaily&#34;,&#34; dataWeekly&#34;或&#34; dataMonthly&#34;),而不是该文字指定的数组变量字符串(dataDaily
,dataWeekly
或dataMonthly
)。
快速解决方案是评估(使用eval()
)选择的值,这样你就可以转换&#34;将字符串放入同名数组中:
var timeSelection = eval( $("#DataType").val() );
所以最终的代码如下:
var dataDaily = [
['CVR', 'TALK'],
[90, 353]
];
var dataWeekly = [
['CVR', 'TALK'],
[225, 893]
];
var dataMonthly = [
['CVR', 'TALK'],
[1602, 4934]
];
$(function () {
// Initial chart
var chart = c3.generate({
data: {
rows: dataDaily,
type: 'pie'
}
});
// Redraw chart depending on which option is selected
$("#DataType").change(function (evt) {
var timeSelection = eval( $("#DataType").val() );
var chart = c3.generate({
data: {
rows: timeSelection,
type: 'pie'
}
});
});
});
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.css">
<select id="DataType">
<option value="dataDaily">Daily</option>
<option value="dataWeekly">Weekly</option>
<option value="dataMonthly">Monthly</option>
</select>
<div id="chart"></div>
&#13;
您还可以在此JSFiddle上看到它正常工作:http://jsfiddle.net/km97cdL3/1/
注意:在开始使用eval()
之前,如果使用不当,您应该注意其风险。 Check this question and the comments for more details