Highcharts:上下文菜单按钮,onclick 函数

Highcharts: Context Menu Button, onclick function

我有一个包含多个图表的页面,我为每个 chart.I 需要在单击任何项​​目时调用 somefunction() 的导出上下文菜单添加特定选项。这绝对有效,但不正确!

这是我使用的代码:

HelloWorld = function () {
    var items = [];
    for (var index = 0; index<5; index++) {
        items.push({text: "items "+index, onclick: function() {
            alert(index);
        }});
    }
    return items;
};

buttons: {
  contextButton: {
    menuItems: HelloWorld()
  }
}

这里有一个 fiddle 证明了我的问题:Fiddle

当任何项目被点击时,onclick 函数 alert(5)! 非常感谢!

这是一个 closure 问题。问题在这里:

for (var index = 0; index<5; index++) {
    items.push({text: "items "+index, onclick: function() {
        alert(index);
    }});
}

在每次迭代中,您将 onclick 的值设置为提醒 index 的函数。但是,每个函数中的 index 变量都绑定到函数外声明的一个 index 变量。而函数运行时他们实际使用的 index 的值是 index 的最终值,即 5.

为了解决这个问题,您可以使用 IIFE (Immediately-Invoked Function Expression) 包装器将 index 的每个值作为新变量 i 传递给匿名函数,其值不会改变随着 index 的变化。

for (var index = 0; index<5; index++) {
    items.push({text: "items "+index, onclick: (function(i) {
        return function(){
            alert(i);
        }
    })(index)});
}

换句话说,包装函数会立即执行,并且 returns 一个新函数,它的行为与原始函数类似,只是它没有绑定到 index 迭代器。

Updated fiddle