使用morris.js基于复选框值切换数据 [英] Toggle data based on checkbox value with morris.js

查看:130
本文介绍了使用morris.js基于复选框值切换数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在制作我想要的morris.js图表时遇到了麻烦.

I'm getting trouble in making what I want morris.js charts to do.

我的目标是能够根据input[type=checkbox]值切换特定行.

My goal is to be able to toggle specific lines based on input[type=checkbox] value.

到目前为止,这是我所做的:

So far here's what I have done:

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> 


问题在于图表会重复显示两条线.


The problem is that the chart duplicates itself with both lines showing up.

任何想法要去哪里调查? (我不要求别人为我编写代码,我只需要一些提示).

Any idea where to investigate to? (I'm not asking for someone to make up the code for me, I just need some tips).

推荐答案

对于可能对解决方案感兴趣的人(可用于切换一行):

For those who might be interested in the solution (works for toggling one line):

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/

这篇关于使用morris.js基于复选框值切换数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆