var funcs = [];
// let's create 3 functions
for (var i = 0; i < 3; i++) {
// and store them in funcs
funcs[i] = function() {
// each should log its value.
console.log("My value: " + i);
};
}
for (var j = 0; j < 3; j++) {
// and now let's run each one to see
funcs[j]();
}Run Code Online (Sandbox Code Playgroud)
它输出这个:
我的价值:3
我的价值:3
我的价值:3
而我希望它输出:
我的价值:0
我的价值:1
我的价值:2
使用事件侦听器导致运行函数的延迟时,会出现同样的问题:
var buttons = document.getElementsByTagName("button");
// let's create 3 …Run Code Online (Sandbox Code Playgroud)问题
当使用AJAX查询远程API时,由于请求的异步特性,它在完成时都会返回。问题是,当我不得不使用不同的条件对相同的API进行迭代调用时,我不知道会返回哪个响应。
问题:是否可以从中传递变量
示例代码:(简体)
n=5;
for(i=0; i < n; i++) {
$.ajax({
url: someURL,
method: post,
// I don't want to have to use async: false, that's bad
// async: false,
data: JSON.stringify(someData),
beforeSend: function(){
console.log("Starting request #"+i)
},
error: function(err, code, text) {
alert("Something went wrong: \n\n" + code + ": " + text);
},
success: function(response) {
console.log("Response for request #"+i)
console.log(response)
}
})
}
Run Code Online (Sandbox Code Playgroud)
问题在于最终的成功功能:我应该看到的是:
Starting request #0
Starting request #1
Starting request #2
Starting request #3 …Run Code Online (Sandbox Code Playgroud) 我是JavaScript的新手.我有6个元素,我想配备非常相似的事件监听器.我有一个工作强力解决方案,我想改进,但(我认为)我有Java Script关闭的麻烦.
工作代码:
elem = document.getElementById("court1button");
elem.addEventListener("click", wassern_id1, false);
elem = document.getElementById("court1xbutton");
elem.addEventListener("click", abbrechen_id1, false);
elem = document.getElementById("court2button");
elem.addEventListener("click", wassern_id2, false);
elem = document.getElementById("court2xbutton");
elem.addEventListener("click", abbrechen_id2, false);
... 4 more times ...
function wassern_id1(event) {
wassern(1, event)
}
function wassern_id2(event) {
wassern(2, event)
}
... 4 more times ...
function abbrechen_id1(event) {
abbrechen(1, event)
}
function abbrechen_id2(event) {
abbrechen(2, event)
}
... 4 more times ...
function wassern(id, event) { ...
function abbrechen(id, event) { ...
Run Code Online (Sandbox Code Playgroud)
当我找到/sf/answers/176442171/并理解为什么它无法工作时,我是一个无效的简单循环.然后我提出了以下代码,这些代码也不起作用,但现在我现在更长时间理解为什么它不起作用.有人可以向我解释并帮助我创建工作代码吗?
for …Run Code Online (Sandbox Code Playgroud)