在Highchart点击事件栏上获取X轴值

时间:2018-08-29 17:05:09

标签: javascript highcharts

好吧,我有一个Highchart栏,显示一些分数,我想要获得的是单击绘图系列时的x轴值(用户ID)。

进行了一些研究,当我单击图表背景时(我正在使用console.log来显示此数据),我能够显示x轴的值,但是我无法单击任何绘图系列(彩色条) )

这是代码段:

var cats=["1.- John :8","2.- Mark :7","3.- Mary :5","4.- Charles :2","5.- Sarah :1"];
var prcs=[2,12,13,11,15];
Highcharts.chart('container', {
    chart: {
        type: 'bar',
      events:{
        click: function(te){
          console.log(prcs[Math.round(te.xAxis[0].value)]);
        }
      }
    },
    title: {
        text: null
    },
	credits: {
		enabled: false
	},
    xAxis: {
        categories: cats,
		lineColor: '#FFFFFF',
		tickColor: 'transparent',
		labels: {
			align: 'left',
			x: 0,
			y: -12,
			style: {
				textOverflow: 'none',
                width:'300px',
				whiteSpace:'normal'//set to normal
			}
		}
    },
    yAxis: {
        min: 0,
        title: {
            text: null,
        },
		labels: {
			enabled: false
		}
    },
    legend: {
		enabled: false
        //reversed: true
    },
    plotOptions: {
        series: {
            stacking: 'normal',
            dataLabels: {
                enabled: true,
                align: 'left',
                color: '#FFFFFF',
                x: 0
            },
            events:{
              click: function(te){
                console.log(this.name);
              }
            }
            //pointPadding: 0,
            //groupPadding: 0
        },
		bar:{
		}
    },
    series:	[{
        name: 'High',
		color: '#009900',
        data: [0,1,0,1,0]
    }, {
        name: 'Mid',
		color: '#FFCC66',
        data: [4,3,0,1,1]
    }, {
        name: 'Low',
		color: '#FF6666',
        data: [4,4,5,1,0]
    }]
});
<script src="https://code.highcharts.com/highcharts.js"></script>

<div id="container" style="height: 210px"></div>

jsFiddle中的相同之处:http://jsfiddle.net/29vfsc4t/5/

如果您单击背景,则将获得用户ID,然后单击任何栏,您将获得“分数”,我需要的是单击栏时获得用户ID。

1 个答案:

答案 0 :(得分:2)

您应该捕获point.event而不是chart.event来获取该点的xAxis类别:

  plotOptions: {
    series: {
      stacking: 'normal',
      dataLabels: {
        enabled: true,
        align: 'left',
        color: '#FFFFFF',
        x: 0
      },
      point: {
        events: {
          click: function(te) {
            console.log(this.category);
            console.log(this.x);
          }
        }
      }
    },
    bar: {}
  },

请注意对console.log(this.category)的更改以显示xAxis名称。