ECharts柱狀圖添加點擊事件

參考:javascript

https://zhuanlan.zhihu.com/p/33050579css

https://blog.csdn.net/sophia_xiaoma/article/details/78055947html

http://www.jb51.net/article/125820.htmjava

https://www.cnblogs.com/zhzhair-coding/p/6953982.html?utm_source=itdadao&utm_medium=referraljquery

 

對於ECharts生成的圖表數據,series區域默認已添加了開啓了點擊方法,可是須要本身的定義函數。ajax

X軸和Y軸默認未開啓點擊事件,須要開啓。json

triggerEvent:trueecharts

本示例實現瞭如下功能:dom

1.點擊柱狀圖時會刷新數據,但不刷新頁面。async

2.數據部分能夠經過ajax函數生成。

3.點擊刷新更新柱狀圖內容。

具體代碼以下:

<!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>]
    <input type="submit" name="" value="刷新" onclick="refresh()">
    <div id="main" style="width: 600px;height:400px;"></div>
    
</body>
<script type="text/javascript">
  function getSeriesData(){

      //根據js方法自己的加載順序,此方法須要定義在myChart前面
      //此處能夠經過後臺生成數據,這樣後臺就無需返回整個option,只須要返回動態的數據部分便可
      // $.ajax({
      //     type: 'GET',
      //     url: "getSeriesData",
      //     cache: false,
      //     async : false,
      //     dataType: 'json',
      //     success: function (result) {
      //         seriesdata = result;
      //     },
      //     error: function (result, XMLHttpRequest, textStatus, errorThrown) {
      //         // 狀態碼
      //         // console.log(XMLHttpRequest.status);
      //         // console.log(XMLHttpRequest.toLocaleString());
      //         // 狀態
      //         // console.log(XMLHttpRequest.readyState);
      //         // 錯誤信息
      //         // console.log(textStatus);
      //     }
      // });

        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);
        seriesdata = [n1, n2, n3, n4, n5, n6];

      return seriesdata;
  }  
</script>
<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 seriesdata = [n1, n2, n3, n4, n5, n6];
        
        var seriesdata ;
        seriesdata=getSeriesData();
        console.log("seriesdata getSeriesData is "+seriesdata);
        
        // 指定圖表的配置項和數據
        var option = {
            title: {
                text: 'ECharts 入門示例'
            },
            tooltip: {},
            legend: {
                data:['銷量']
            },
            xAxis: {
                data: ["襯衫","羊毛衫","雪紡衫","褲子","高跟鞋","襪子"],
                triggerEvent:true,
                axisTick: {
                    alignWithLabel: true //座標值是否在刻度中間
                }
                
            },
            yAxis: {triggerEvent:true},
            series: {
                name: '銷量',
                type: 'bar',
                //data: [n1, n2, n3, n4, n5, n6],
                data : seriesdata,
                itemStyle: {  
                    normal: {  
                        color: function(params) {
                      var colorList = ['#2eddc1','#FCCE10','#E87C25','#277bbb','#E87fff','#277aaa'];
                            //若返回的list長度不足,不足部分自動顯示爲最後一個顏色
                        return colorList[params.dataIndex]
                      },
                        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();   
      
      //局部刷新main內容
      //此處沒有用經常使用的刷新div等方法,而是直接改變了option的值,而後從新賦值給myChart
      console.log("refresh");
      option.title.text='入門';
      // option.series.data[0] = Math.floor(Math.random()*50+1);
      // option.series.data[1] = Math.floor(Math.random()*50+1);
      // option.series.data[2] = Math.floor(Math.random()*50+1);
      // option.series.data[3] = Math.floor(Math.random()*50+1);
      // option.series.data[4] = Math.floor(Math.random()*50+1);
      // option.series.data[5] = Math.floor(Math.random()*50+1);
      
      //console.log(option.series.data[0]);
      //var v1 = Math.floor(Math.random()*50+1);
      //option.series.data[0] = v1;

      //簡化方法,調用getSeriesData更新數據。
      option.series.data = getSeriesData();
      
      myChart.setOption(option);
  };     
  
</script>
</html>

 

將部份內容放入到方法中,如X軸數據部分,series的data部分,方便將樣式與數據進行分離。

<!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>]
    <input type="submit" name="" value="刷新" onclick="refresh()">
    <div id="main" style="width: 600px;height:400px;"></div>
    
</body>
<script type="text/javascript">
  function getSeriesData(){

      //根據js方法自己的加載順序,此方法須要定義在myChart前面
      //此處能夠經過後臺生成數據,這樣後臺就無需返回整個option,只須要返回動態的數據部分便可
      // $.ajax({
      //     type: 'GET',
      //     url: "getSeriesData",
      //     cache: false,
      //     async : false,
      //     dataType: 'json',
      //     success: function (result) {
      //         seriesdata = result;
      //     },
      //     error: function (result, XMLHttpRequest, textStatus, errorThrown) {
      //         // 狀態碼
      //         // console.log(XMLHttpRequest.status);
      //         // console.log(XMLHttpRequest.toLocaleString());
      //         // 狀態
      //         // console.log(XMLHttpRequest.readyState);
      //         // 錯誤信息
      //         // console.log(textStatus);
      //     }
      // });

        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);
        seriesdata = [n1, n2, n3, n4, n5, n6];

      return seriesdata;
  }  

  function getxAxisData(){
    //一樣適用以ajax的方式從後臺獲取數據
    xAxisData = ["襯衫","羊毛衫","雪紡衫","褲子","高跟鞋","襪子"];
    return xAxisData;
  }

  function getSaleOption(){
      saleOption = {
            title: {
                text: 'ECharts 入門示例'
            },
            tooltip: {},
            legend: {
                data:['銷量']
            },
            xAxis: {
                // data: ["襯衫","羊毛衫","雪紡衫","褲子","高跟鞋","襪子"],
                data : getxAxisData(),
                triggerEvent:true,
                axisTick: {
                    alignWithLabel: true //座標值是否在刻度中間
                }
                
            },
            yAxis: {triggerEvent:true},
            series: {
                name: '銷量',
                type: 'bar',
                //data: [n1, n2, n3, n4, n5, n6],
                // data : seriesdata,
                data : getSeriesData(),
                itemStyle: {  
                    normal: {  
                        color: function(params) {
                      var colorList = ['#2eddc1','#FCCE10','#E87C25','#277bbb','#E87fff','#277aaa'];
                            //若返回的list長度不足,不足部分自動顯示爲最後一個顏色
                        return colorList[params.dataIndex]
                      },
                        label: {  
                            show: true,  
                            position: 'top'
                        }  
                    }  
                }
            }
        };

        return saleOption;
  }
  

</script>
<script type="text/javascript">
        // 基於準備好的dom,初始化echarts實例
        var myChart = echarts.init(document.getElementById('main'));
        
        // 指定圖表的配置項和數據
        var option = getSaleOption();
        // 使用剛指定的配置項和數據顯示圖表。
        myChart.setOption(option);

        myChart.on('click', function (params) { 
        //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(){             
      
      //局部刷新series內容
      //此處沒有用經常使用的刷新div等方法,而是直接改變了option的值,而後從新賦值給myChart
     
      //簡化方法,調用getSeriesData更新數據。
      option.series.data = getSeriesData();
      
      myChart.setOption(option);
  };     
  
</script>
</html>
相關文章
相關標籤/搜索