简体   繁体   English

可从jQuery中的闭包访问可变变量

[英]Mutable variable is accessible from closure in jQuery

I know this is probably "double-posted". 我知道这可能是“双重张贴”。 But I am not able to assign the solutions to my problem. 但是我无法为我的问题分配解决方案。

I have 6 fileupload input fields. 我有6个fileupload输入字段。 Whenever they change, I wanna alert "Changed!". 每当他们更改时,我都想提醒“已更改!”。 I want to iterate through thoes 6 fileupload id's with a for-loop. 我想通过for循环遍历6种文件上传ID。 Now, it gives me the error on variable i "Mutable variable is accessible from closure". 现在,它给了我关于变量i“可从闭包访问可变变量”的错误。 I saw some solutions for this. 我看到了一些解决方案。 But I'm not able to use these solutions for my problem. 但是我无法使用这些解决方案解决我的问题。

function fileUploadCheck() {
    for (var i = 1; i <= 6; i++) {
        $("document").ready(function () {
            $("#SOMEID"+i).change(function () {
                alert('changed!');
            });
        });
    }
}

jQuery uses implicit iteration . jQuery使用隐式迭代 You don't have to loop manually. 您不必手动循环。

$("input[type=file]").change(function(event) {
  // check your console to see the value of `this`
  console.log(this, "changed");
});

From the jQuery .each docs 来自jQuery .each文档

Note: most jQuery methods that return a jQuery object also loop through the set of elements in the jQuery collection — a process known as implicit iteration . 注意:大多数返回jQuery对象的jQuery方法也会循环遍历jQuery集合中的元素集—这个过程称为隐式迭代 When this occurs, it is often unnecessary to explicitly iterate with the .each() method: 发生这种情况时,通常无需使用.each()方法进行显式迭代:

// The .each() method is unnecessary here:
$( "li" ).each(function() {
  $( this ).addClass( "foo" );
});

// Instead, you should rely on implicit iteration:
$( "li" ).addClass( "bar" );

Regarding your "Mutable variable is accesible from closure", see this simplified example 关于“可变变量可以从闭包访问”,请参见此简化示例

for (var i=1; i<=6; i++) {
  setTimeout(function() {
    console.log(i);
  }, 100);
}

// 777777
// ALL SEVENS? WTF

The reason for that is, the closure depends on i , but i is changing outside of the closure. 其原因是,闭包取决于i ,但是i在闭包之外进行更改。 By the time any function is run, i has already set to 7 , so the logged output for each function is 7 . 在运行任何功能时, i已经设置为7 ,因此每个功能的记录输出为7

If you use the method I have above, you won't have to worry about this at all. 如果您使用上面介绍的方法,则完全不必担心。 If you are still curious how you would fix this, please see 如果您仍然好奇如何解决此问题,请参阅

for (var i=1, fn; i<=6; i++) {

  fn = (function(n) {
    console.log(n);
  })(i);

  setTimeout(fn, 100);
}

// 123456
// YAY

Now each function is properly "bound" with an immutable i input; 现在,每个函数都通过不变的i输入正确地“绑定”了; meaning the value of i will not change inside of the closure-wrapped function. 表示i的值在闭包函数内部不会改变。 Check out Function.prototype.bind if you're interested in shortcuts ^.^ 如果您对快捷方式^。^感兴趣,请查看Function.prototype.bind

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM