javascript - 在鼠标事件的 for 循环中赋值

标签 javascript loops

为什么我总是得到分配给变量的最后一个值 即使我已经将它封装在一个函数中?

当触发鼠标松开事件并调用 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/

相关文章:

c++ - 尝试打印数组什么都不打印

angularjs - 遍历对象数组Angular 2

r - 有没有办法简化 R 中利用循环的函数?

javascript - 从 Google Universal Analytics 获取推荐和事件信息

javascript - 使图像随机 move onclick

javascript - 动画一次 Phaser

javascript - 在现有数组的中间插入一个数组。保持现有引用不变

PHP如何查找重复项

javascript - 在react js中按日期对数据进行排序

每个人重复一个模型 100 次