.forEach循环:使用变量 [英] .forEach loop: use variable
问题描述
我循环遍历一组16个ID并为每个ID分配一个 eventListener
。我想向我的php文件发送一个数字(第一个id为1,第二个为2,等等),但似乎 i
比我更有活力我希望它是。每个id发送 17
。
I'm looping through a set of 16 ids and assigning an eventListener
to each one. I want to send a number to my php file (1 for the first id, 2 for the second, etc, etc), but it seems that i
is more dynamic than I'd like it to be. Every id sends 17
.
klasses.forEach(function(klass){
var svgElement = svgDoc.getElementById(klass); //get the inner element by id
svgElement.addEventListener("mouseup",function(){
$.ajax({
type: "POST",
url: "buildService.php",
data: { "service" : i}
}).done(function(msg){
alert(lameArray[i]);
$("#modalSpan").html(msg);
$("#modmodal").modal();
});
});
i++;
});
如何将每一个设置为特定数字?我也尝试过:
How can I set each one to a specific number? I've also tried:
var lameArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];
...
data: { "service" : lameArray[i]}
推荐答案
什么是我
?问题是 i
是一个全局变量,或者是 forEach
循环之外的变量,所以当 mouseup
事件被触发, istant中 i
的值被使用,而不是一个它定义了事件监听器。
What's i
? The problem is that i
is a global variable, or a variable outside the forEach
cycle anyway, so when the mouseup
event is triggered, the value of i
in that istant is used, and not the one it had when the event listener is defined.
请注意,因为你使用 forEach
,回调函数实际上是用第二个参数调用的,它是计数器。所以你可以使用:
Mind you, since you're using forEach
, that the callback function actually is called with a second parameter, which is the counter. So you can use:
klasses.forEach(function(klass, i) {
...
});
现在, i
是一个变量 forEach
范围,并满足您的目的。 ( forEach
也使用第三个参数调用回调函数,即你自己的集合本身 - klasses
。)
Now, i
is a variable in the forEach
scope, and serves your purposes. (forEach
calls the callback function with a third parameter too, that is the collection itself - klasses
in your case.)
注意:由于您使用的是jQuery,因此您应该使用更类似jQuery的样式进行编码。所以改变你的代码是这样的:
Note: since you're using jQuery, you should code with a more "jQuery-like" style. So change your code in something like this:
$.each(klasses, function(i, klass) {
$("#" + klass).mouseup(function(){
$.ajax({
type: "POST",
url: "buildService.php",
data: {service: i + 1}
...
});
});
});
这篇关于.forEach循环:使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!