[英]Toggle data based on checkbox value with morris.js
我在制作morris.js
图表时遇到了麻烦。
我的目标是能够根据input[type=checkbox]
值切换特定行。
到目前为止,这是我所做的:
JS代码
var morris = Morris.Line({
element: 'line-example',
data: [
{ y: '2006', a: 100, b: 90 },
{ y: '2007', a: 75, b: 65 },
{ y: '2008', a: 50, b: 40 },
{ y: '2009', a: 75, b: 65 },
{ y: '2010', a: 50, b: 40 },
{ y: '2011', a: 75, b: 65 },
{ y: '2012', a: 100, b: 90 }
],
xkey: 'y',
ykeys: ['a', 'b'],
labels: ['Series A', 'Series B']
});
jQuery(function($) {
$('#activate').on('change', function() {
var isChecked = $(this).is(':checked');
console.log(isChecked);
if(!isChecked) {
morris = Morris.Line({
element: 'line-example',
ykeys: ['a']
});
}
});
});
HTML代码
<body>
<div id="line-example"></div>
<br/>
<input type="checkbox" id="activate" checked="checked"/> Activate
</body>
问题在于图表会重复显示两条线。
任何想法去哪里调查? (我不要求别人为我编写代码,我只需要一些提示)。
对于可能对解决方案感兴趣的人(可用于切换一行):
JS代码
<script>
function data(toggle) {
var ret = [
{ y: '2006', a: 100, b: 90 },
{ y: '2007', a: 75, b: 65 },
{ y: '2008', a: 50, b: 40 },
{ y: '2009', a: 75, b: 65 },
{ y: '2010', a: 50, b: 40 },
{ y: '2011', a: 75, b: 65 },
{ y: '2012', a: 100, b: 90 }
];
if(toggle == 1) {
for(var i = 0; i < ret.length; i++)
delete ret[i].b;
}
return ret;
};
var morris = Morris.Line({
element: 'line-example',
data: data(),
xkey: 'y',
ykeys: ['a', 'b'],
labels: ['Series A', 'Series B']
});
jQuery(function($) {
$('#activate').on('change', function() {
var isChecked = $(this).is(':checked');
if(isChecked)
{
morris.setData(data(0));
} else {
morris.setData(data(1));
}
});
});
</script>
工作小提琴: http : //jsfiddle.net/4ztbu8oo/
我对您的代码进行了一些编辑,然后在其中显示了第三行,该行响应被检查,但是有一个错误,当第二行未选中时,它会带回第三行。
/*
* Play with this code and it'll update in the panel opposite.
*
* Why not try some of the options above?
*/
function data(toggle) {
var ret = [
{ y: '2006', a: 100, b: 90, c:80},
{ y: '2007', a: 75, b: 65, c:80 },
{ y: '2008', a: 50, b: 40, c:80 },
{ y: '2009', a: 75, b: 65, c:80 },
{ y: '2010', a: 50, b: 40, c:80 },
{ y: '2011', a: 75, b: 65, c:80 },
{ y: '2012', a: 100, b: 90, c:80 }
];
if(toggle == 1) {
for(var i = 0; i < ret.length; i++)
delete ret[i].b;
}
if(toggle == 2) {
for(var i = 0; i < ret.length; i++)
delete ret[i].c;
}
return ret;
};
var morris = Morris.Line({
element: 'line-example',
data: data(),
xkey: 'y',
ykeys: ['a', 'b', 'c'],
labels: ['Series A', 'Series B', 'Series C']
});
jQuery(function($) {
$('#activate').on('change', function() {
var isChecked = $(this).is(':checked');
if(isChecked)
{
morris.setData(data(0));
} else {
morris.setData(data(1));
}
});
});
jQuery(function($) {
$('#activate1').on('change', function() {
var isChecked = $(this).is(':checked');
if(isChecked)
{
morris.setData(data(0));
} else {
morris.setData(data(2));
}
});
});
这是您的小提琴编辑的地方。 并感谢您有这个问题!
我为morrisjs创建了一个包装器,使您可以切换数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.