2016-12-05 61 views
1
for (var i = 0; i < 8; i++) { 
    $("#image" + i).click(function() { 
     console.log("test: " + i); 
    }); 
} 

我等待测试:0,测试:1,测试:2 ...在这里的控制台,当我点击我的图片,但只有有: “测试:8” 消息。它为什么这样工作? 如何保存i变量的当前值?我需要做的是这样的:JQuery的click事件如何与其中的全局变量一起工作?

for (var i = 0; i < 8; i++) { 
    $("#image" + i).click(function() { 
     $("#anotherImage" + i).css("opacity", "0.5"); 
    }); 
} 

我有8个anotherImages用的ID:anotherImage0,anotherImage1,...,anotherImage7 :)

回答

2

这是因为i并不仅仅作用域你的循环块,但是全局范围或其父功能。一旦你的循环完成,它的价值就是它增加的次数的总和。为了加强你的目标实现了块作用域,你可以使用ES6的let变量赋值:

for (let i = 0; i < 8; i++) { 
 
    $("#image" + i).click(function() { 
 
    console.log("test: " + i); 
 
    }); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<img id="image1" src="http://placehold.it/350x150" width="350" height="150" /> 
 
<img id="image2" src="http://placehold.it/350x150" width="350" height="150" /> 
 
<img id="image3" src="http://placehold.it/350x150" width="350" height="150" /> 
 
<img id="image4" src="http://placehold.it/350x150" width="350" height="150" /> 
 
<img id="image5" src="http://placehold.it/350x150" width="350" height="150" /> 
 
<img id="image6" src="http://placehold.it/350x150" width="350" height="150" /> 
 
<img id="image7" src="http://placehold.it/350x150" width="350" height="150" /> 
 
<img id="image8" src="http://placehold.it/350x150" width="350" height="150" />


或者你可以在你的循环创建IIFE,这将执行块作用域但伊莫let是更清洁:

for (var i = 0; i < 8; i++) { 
 
    (function(index) { 
 
    $("#image" + index).click(function() { 
 
     console.log("test: " + index); 
 
    }); 
 
    })(i); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<img id="image1" src="http://placehold.it/350x150" width="350" height="150" /> 
 
<img id="image2" src="http://placehold.it/350x150" width="350" height="150" /> 
 
<img id="image3" src="http://placehold.it/350x150" width="350" height="150" /> 
 
<img id="image4" src="http://placehold.it/350x150" width="350" height="150" /> 
 
<img id="image5" src="http://placehold.it/350x150" width="350" height="150" /> 
 
<img id="image6" src="http://placehold.it/350x150" width="350" height="150" /> 
 
<img id="image7" src="http://placehold.it/350x150" width="350" height="150" /> 
 
<img id="image8" src="http://placehold.it/350x150" width="350" height="150" />
在JS个

+0

好的答案!但**“反而升起并且具有全局范围。”**只要我们没有看到完整的代码,我们不能确定变量的范围。我们只能知道功能共享相同的范围。在这种情况下,变量提升如何相关? – bugwheels94

+2

啊,很好的接收!修改我的解释以反映这一点。好看。 –

3

功能记住他们的环境,这就是为什么在JS的所有功能都是关闭

for (var i = 0; i < 8; i++) { 
    (function(index){ //now index variable will be correct as they are passed to each function instead of sharing same i 
     $("#image" + index).click(function() { 
      console.log("test: " + index); 
     }); 
    })(i); 
} 

PS:如果有与ES6使用没有问题,那么也请尝试其他的答案与使用让建议