Highcharts - fire legendItemClick event

2019-04-23 14:20发布

I want to fire the same event that it's fired when you select an item legend but from an external html button. Is it possible?

I've created a jsfiddle to show it: http://jsfiddle.net/YcJF8/1/ .

$('#container').highcharts({
                    chart : {
                        type : 'spline',
                    },

                    xAxis : {
                        categories : ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
                    },

                    series : [{
                        data : [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4],

                    }],

                    plotOptions : {
                        series : {

                        cursor : 'pointer',
                    }
                },
});

$('#button').click(function() {
        alert("Fire legenditemclick event");
});

In this jsfiddle, I have a button and I want that when I click the button it fires an event or something that chart detects and acts like item legend (series 1) was clicked.

Thank you very much

2条回答
一纸荒年 Trace。
2楼-- · 2019-04-23 14:30

Just use:

$($('.highcharts-legend-item')[0]).click()

Where the 0 is the index of the series you wish to 'click'.

Update fiddle.

EDITS

  • highcharts-legend-item is the class of each entry in the legend. I discovered this by inpecting the legend using chrome developer tools.
  • the $('.highcharts-legend-item') is a jquery selector to return an array of all elements of that class. I select the first one by index and the $() it to convert it into a jquery object
  • The .click is this: http://api.jquery.com/click/
查看更多
forever°为你锁心
3楼-- · 2019-04-23 14:30

I think the answer with defining the click on

$('.highcharts-legend-item')[0]) 

is not the best one. It is very "expensive" since the DOM is probably heavy. My solution is generally based on CSS. You can set the position of highchart legend items right above the custom elements that you want to use and every item should have width&height same as the custom HTML element. Highchart elements should have opacity value 0 so they are not visible. So when you click on your element,in fact, you are clicking on the highchart legend item. If you want to set some CSS for your custom element you should define legendItemClick callback:

plotOptions: {
    series: {
        events: {
            legendItemClick: function() {
                var legenedItemIndex = this.index // index of highchart legend item
                $("your html element:eq(" + legenedItemIndex + ")") //do something with your element
            }
        }
    }
}
查看更多
登录 后发表回答