this is my html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Something</title>
</head>
<body>
<a href="http://www.google.com">Try Me!</a>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script>
$("a").click(function(event){
for(id=0;id<=10;id++){
setTimeout(function() {
var local_id = id;
window.open("http://www.mysite.com/characterID="+local_id,"", "win"+local_id, "width=100,height=100,resizable");
}, 3000*id);
}
event.preventDefault();
});
</script>
</body>
</html>
This link is opening each window 3 seconds after the next.
This is the row I need: http://www.mysite.com/characterID=1, http://www.mysite.com/characterID=2, http://www.mysite.com/characterID=3...
But it always opens http://www.mysite.com/characterID=11
How can I fix it?
Thank you…
This is a common issue.
You’re overwriting
local_idin the loop, and always referring to the same variable when the code runs. This is because JavaScript does not have block scope, just function scope.So to scope the
id, you need to invoke a function, and define the variable (or function parameter) there.Or a similar patter would be to have the function return a function to the loop.