参考:
https://zhuanlan.zhihu.com/p/33050579
https://blog.csdn.net/sophia_xiaoma/article/details/78055947
http://www.jb51.net/article/125820.htm
https://www.cnblogs.com/zhzhair-coding/p/6953982.html?utm_source=itdadao&utm_medium=referral
对于ECharts生成的图表数据,series区域默认已添加了开启了点击方法,但是需要自己的定义函数。
X轴和Y轴默认未开启点击事件,需要开启。
triggerEvent:true
具体代码如下
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>ECharts</title> <!-- <script src="http://echarts.baidu.com/dist/echarts.min.js"></script> --> <script src="https://cdn.bootcss.com/echarts/4.0.2/echarts.js"></script> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script> </head> <body> <!-- 为ECharts准备一个具备大小(宽高)的Dom --> 您选择了X轴的标签[<span id="xAxisTag"></span>],他的值为[<span id="barValue"></span>] <div id="main" style="width: 600px;height:400px;"></div> </body> <script type="text/javascript"> // 基于准备好的dom,初始化echarts实例 var myChart = echarts.init(document.getElementById('main')); var n1 = Math.floor(Math.random()*50+1); var n2 = Math.floor(Math.random()*50+1); var n3 = Math.floor(Math.random()*50+1); var n4 = Math.floor(Math.random()*50+1); var n5 = Math.floor(Math.random()*50+1); var n6 = Math.floor(Math.random()*50+1); // 指定图表的配置项和数据 var option = { title: { text: 'ECharts 入门示例' }, tooltip: {}, legend: { data:['销量'] }, xAxis: { data: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"], triggerEvent:true }, yAxis: {triggerEvent:true}, series: { name: '销量', type: 'bar', data: [n1, n2, n3, n4, n5, n6], itemStyle: { normal: { label: { show: true, position: 'top' } } } } }; // 使用刚指定的配置项和数据显示图表。 myChart.setOption(option); myChart.on('click', function (params) { // 当componentType == "xAxis"或者 ==“yAxisx”时,取被点击时坐标轴的值params.value // alert("单击了"+params.componentType+"x轴标签"+params.value); if(params.componentType == "xAxis"){ alert("单击了"+params.value+"x轴标签"); }else if (params.componentType == "yAxis") { alert("单击了"+params.value+"y轴标签"); } else{ alert("单击了"+params.name+"柱状图"+params.value); } // invalid start // 获取data长度 // alert(option.series[0].data.length); // 获取地N个data的值 // alert(option.series[0].data[3]); // 获取series中param.dataIndex事件对应的值 // alert(params.dataIndex); // alert(option.series[params.seriesIndex].data[params.dataIndex]); //invalid end // alert(param.value); // 获取xAxis当前点击事件索引对应的值,可以用作传参 // alert("test "+option.xAxis.data[params.dataIndex]); //param.dataIndex 获取当前点击索引, // alert(param.dataIndex); // 当前点击事件位于series中的索引 // alert(param.seriesIndex); //param具体包含的参数见 https://blog.csdn.net/allenjay11/article/details/76033232 updatePage(option.xAxis.data[params.dataIndex],params.value); // refresh(); }); </script> <script type="text/javascript"> function updatePage(tag, value){ var xAxisTag = $("#xAxisTag"); xAxisTag.html(tag); var barValue = $("#barValue"); barValue.html(value); }; function refresh(){ // 刷新页面 // location.reload(); window.location.reload(); }; </script> </html>