Кнопка «Скрыть все серии» на графике CanvasJS (использование javascript foreach) - PullRequest
0 голосов
/ 05 июня 2018

Вопрос, связанный с CanvasJS, но, вероятно, любой эксперт по чистому javascript может помочь.

Мне нужна кнопка, чтобы скрыть / показать все элементы в графике canvasjs.Существует рабочий код, который может скрыть элемент с помощью индекса массива:

chart.options.data[0].visible = !chart.options.data[0].visible;

Я пытаюсь просмотреть массив, но он не работает, очевидно, мой код неверен:

chart.options.data.forEach(visible = !visible);

Как это исправить?

Полный фрагмент кода:

 var chart = new CanvasJS.Chart("chartContainer",
    {
      title:{
      text: "Test Button to Hide All Series"  
      },
      
      legend: {
            cursor: "pointer",
            itemclick: function (e) {
                //console.log("legend click: " + e.dataPointIndex);
                //console.log(e);
                if (typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
                    e.dataSeries.visible = false;
                } else {
                    e.dataSeries.visible = true;
                }
 
                e.chart.render();
            }
        },
      
      data: [
      { 
        showInLegend: true,
        type: "line",
        dataPoints: [
        { x: 10, y: 5 },
        { x: 20, y: 9},
        { x: 30, y: 17 },
        { x: 40, y: 32 },
        { x: 50, y: 22 },
        { x: 60, y: 14 },
        { x: 70, y: 25 },
        { x: 80, y: 18 },
        { x: 90, y: 20}
      
        ]
      },
        {
        showInLegend: true,
        type: "line",
        dataPoints: [
        { x: 10, y: 31 },
        { x: 20, y: 35},
        { x: 30, y: 30 },
        { x: 40, y: 35 },
        { x: 50, y: 35 },
        { x: 60, y: 38 },
        { x: 70, y: 38 },
        { x: 80, y: 34 },
        { x: 90, y: 44}
      
        ]
      },
        {
        showInLegend: true,
        type: "line",
        dataPoints: [
        { x: 10, y: 25 },
        { x: 20, y: 30},
        { x: 30, y: 20 },
        { x: 40, y: 45 },
        { x: 50, y: 30 },
        { x: 60, y: 10 },
        { x: 70, y: 15 },
        { x: 80, y: 18 },
        { x: 90, y: 20}
      
        ]
      }
      ]
    });
 
    chart.render();
    
 document.getElementById("showAllSeries").onclick =  function(){
   //Works for a single element using index:
   chart.options.data[0].visible = !chart.options.data[0].visible;
   //Doesn't work, need to modify
   //chart.options.data.forEach(visible = !visible);
   chart.render();
 };
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<br/>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
<center><button id= "showAllSeries" style= "margin: 10px;">Show/Hide All series</button></center>

UP: Найдено решение с помощью цикла for:

   for (var i = 0; i < chart.options.data.length; i++) {
   chart.options.data[i].visible = !chart.options.data[i].visible;
   }

Но все же интересно, как оно должно работать с Еогеасп

Ответы [ 2 ]

0 голосов
/ 06 июня 2018

Спасибо Vishwas за подробный ответ.В общем, да, и for & forEach прекрасно подходят здесь.Я отмечу это как правильное, но это помогло мне получить более сжатое решение, используя forEach, что я ожидал:

document.getElementById(""showAllSeries"").onclick =  function(){
 chart.options.data.forEach(function(dataSeries) {
    dataSeries.visible = !dataSeries.visible })
    chart.render();
    };

Оставлю это здесь для истории также:

 var chart = new CanvasJS.Chart("chartContainer",
    {
      title:{
      text: "Test Button to Hide All Series"  
      },
      
      legend: {
            cursor: "pointer",
            itemclick: function (e) {
                //console.log("legend click: " + e.dataPointIndex);
                //console.log(e);
                if (typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
                    e.dataSeries.visible = false;
                } else {
                    e.dataSeries.visible = true;
                }
 
                e.chart.render();
            }
        },
      
      data: [
      { 
        showInLegend: true,
        type: "line",
        dataPoints: [
        { x: 10, y: 5 },
        { x: 20, y: 9},
        { x: 30, y: 17 },
        { x: 40, y: 32 },
        { x: 50, y: 22 },
        { x: 60, y: 14 },
        { x: 70, y: 25 },
        { x: 80, y: 18 },
        { x: 90, y: 20}
      
        ]
      },
        {
        showInLegend: true,
        type: "line",
        dataPoints: [
        { x: 10, y: 31 },
        { x: 20, y: 35},
        { x: 30, y: 30 },
        { x: 40, y: 35 },
        { x: 50, y: 35 },
        { x: 60, y: 38 },
        { x: 70, y: 38 },
        { x: 80, y: 34 },
        { x: 90, y: 44}
      
        ]
      },
        {
        showInLegend: true,
        type: "line",
        dataPoints: [
        { x: 10, y: 25 },
        { x: 20, y: 30},
        { x: 30, y: 20 },
        { x: 40, y: 45 },
        { x: 50, y: 30 },
        { x: 60, y: 10 },
        { x: 70, y: 15 },
        { x: 80, y: 18 },
        { x: 90, y: 20}
      
        ]
      }
      ]
    });
 
    chart.render();
    
    document.getElementById("showAllSeries").onclick=function(){
      chart.options.data.forEach(function(dataSeries){
		dataSeries.visible = !dataSeries.visible
            })
     chart.render();
     };
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<br/>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
<center><button id= "showAllSeries" style= "margin: 10px;">Show/Hide All series</button></center>
0 голосов
/ 06 июня 2018

forEach - это метод Array, который можно использовать для выполнения функции для каждого элемента в массиве.С другой стороны, for является более гибким циклом.

В вашем случае вы можете скрыть все нажатия кнопки dataSeries, используя кнопки for или forEach.Проверьте код ниже:

var chart = new CanvasJS.Chart("chartContainer", {
	title:{
		text: "Test Button to Hide All Series"  
	},

	legend: {
		cursor: "pointer",
		itemclick: function (e) {
			if (typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
				e.dataSeries.visible = false;
			} else {
				e.dataSeries.visible = true;
			}
			e.chart.render();
		}
	},

	data: [
		{ 
		showInLegend: true,
		type: "line",
		dataPoints: [
			{ x: 10, y: 5 },
			{ x: 20, y: 9 },
			{ x: 30, y: 17 },
			{ x: 40, y: 32 },
			{ x: 50, y: 22 },
			{ x: 60, y: 14 },
			{ x: 70, y: 25 },
			{ x: 80, y: 18 },
			{ x: 90, y: 20 }
		]
		},
		{
		showInLegend: true,
		type: "line",
		dataPoints: [
			{ x: 10, y: 31 },
			{ x: 20, y: 35 },
			{ x: 30, y: 30 },
			{ x: 40, y: 35 },
			{ x: 50, y: 35 },
			{ x: 60, y: 38 },
			{ x: 70, y: 38 },
			{ x: 80, y: 34 },
			{ x: 90, y: 44 }
		]
		},
		{
		showInLegend: true,
		type: "line",
		dataPoints: [
			{ x: 10, y: 25 },
			{ x: 20, y: 30 },
			{ x: 30, y: 20 },
			{ x: 40, y: 45 },
			{ x: 50, y: 30 },
			{ x: 60, y: 10 },
			{ x: 70, y: 15 },
			{ x: 80, y: 18 },
			{ x: 90, y: 20 }
		]
		}
	]
});

chart.render();

document.getElementById("showAllSeries").onclick =  function(){
	chart.options.data.forEach(function(dataSeries) {
  	if (typeof (dataSeries.visible) === "undefined" || dataSeries.visible) {
			dataSeries.visible = false;
		} else {
			dataSeries.visible = true;
		}
	});
	/*var dataSeries;
  	for(var i = 0; i < chart.data.length; i++){
  	dataSeries = chart.options.data[i];
		if (typeof (dataSeries.visible) === "undefined" || dataSeries.visible) {
			dataSeries.visible = false;
		} else {
			dataSeries.visible = true;
		}
	}*/  
	chart.render();
};
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 260px; width: 100%;"></div>
<center><button id= "showAllSeries" style= "margin: 10px;">Show/Hide All series</button></center>
...