javascript - 在鼠标事件的 for 循环中赋值
问题描述
为什么我总是得到分配给变量的最后一个值,即使我已经将它包含在一个函数中?
当触发事件 mouse up 并调用 getGoogleFiles 时,将调用分配给 resourceId 的最后一个值。我不明白。
for ( var i in arrayObj) {
var resourceId = arrayObj[i].ResourceId;
entity_list.onmouseup = function(event) {
parent.changeButtonState(this, event);
(function(resourceId) {
getGoogleFiles(resourceId);
})(resourceId);
}
}
注意:这与其他 JavaScript 问题不同,因为不会触发 onmouseup
我按照这里提到的另一个函数的创建: JavaScript 闭包内循环 - 简单的实际示例
for ( var i in arrayObj) {
entity_list.onmouseup = function(event) {
parent.changeButtonState(this, event);
testing(arrayObj[i].ResourceId);
}
}
function testing(index){
return function() { getGoogleFiles(index); };
}
但是当“entity_list”的元素被触发时,什么也没有发生。我无法使用let
,因为我使用的特定浏览器返回 SyntaxError
SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
谢谢!
解决方案
你需要用来testing()
创建监听函数,而不是你在里面调用的东西。
for (var i in arrayObj) {
entity_list.onmouseup = testing(arrayObj[i].ResourceId, parent);
}
function testing(index, parent) {
return function(event) {
parent.changeButtonState(this, event);
getGoogleFiles(index);
};
}
forEach()
但是如果你使用而不是循环,你就不必经历任何这些for
,因为它会obj
在每次迭代中创建一个新的范围。
arrayObj.forEach(function(obj) {
entity_list.onmouseup = function(event) {
parent.changeButtonState(this, event);
testing(obj.ResourceId);
}
});
推荐阅读
- sql - 将数据行转换为列并按月显示
- javascript - highchart y 轴范围 0-100 200 300 后 1k 2k 和 3k
- javascript - 角度解析器无权访问角度服务属性
- ibm-cloud - 如何将日志数据发送到 IBM Cloud 上的 Log Analysis 服务
- javascript - electron.js 打印功能,具有页面大小、dpi、布局、主进程的边距设置
- css - 如何使用 CSS 更改 Angular-UI Bootstrap Datepicker 弹出窗口的样式?
- r - 迭代器的迭代器?
- c# - .NET 二进制序列化程序是否对程序集信息进行编码?
- sql-server - SQL SERVER 中的确切月份差异
- angular - 如何将.env文件中的变量传递给angular6 environment.ts文件