MHS*_*MHS 3 javascript onclick highcharts
我有一个包含多个图表的页面,并且我为每个图表的导出上下文菜单添加了特定选项.我需要在单击任何项目时调用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()
}
}
Run Code Online (Sandbox Code Playgroud)
点击任何项目时,点击功能提醒(5)!非常感谢!
这是一个封闭问题.问题出在这里:
for (var index = 0; index<5; index++) {
items.push({text: "items "+index, onclick: function() {
alert(index);
}});
}
Run Code Online (Sandbox Code Playgroud)
在每次迭代中,您将设置值onclick作为警报的函数index.但是,index每个函数中的变量都绑定到index函数外部声明的一个变量.和价值index,他们将通过实际的功能运行的时间用的是的终值index,即5.
为了解决这个问题,您可以使用IIFE(立即调用的函数表达式)包装器将每个值index作为新变量传递给匿名函数,该值i的值不会随更改而index变化.
for (var index = 0; index<5; index++) {
items.push({text: "items "+index, onclick: (function(i) {
return function(){
alert(i);
}
})(index)});
}
Run Code Online (Sandbox Code Playgroud)
换句话说,包装函数立即执行并返回一个新函数,它的行为与原始函数类似,只是它没有绑定到index迭代器.
| 归档时间: |
|
| 查看次数: |
1053 次 |
| 最近记录: |