为什么我总是得到分配给变量的最后一个值 即使我已经将它封装在一个函数中?
当触发鼠标松开事件并调用 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 closure inside loops – simple practical example
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
语法错误:严格模式之外尚不支持 block 作用域声明(let、const、函数、类)
谢谢!
最佳答案
您需要使用 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);
}
});
关于javascript - 在鼠标事件的 for 循环中赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55947333/