首页 > 解决方案 > 在鼠标事件的 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

谢谢!

标签: javascriptloops

解决方案


你需要用来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);
  }
});


推荐阅读