<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Ovi Maps API Example</title>
</head>
<body>
<button id="butt1" name="butt" type="button">Click Me!</button>
<button id="butt2" name="butt" type="button">Click Me!</button>
<button id="butt3" name="butt" type="button">Click Me!</button>
</body>
<script src="jquery.js" type="text/javascript" charset="utf-8"></script>
<script src="foo.js" type="text/javascript" charset="utf-8"></script>
</html>
and…
$(document).ready(function() {
//alert("ready");
var myClickFunctions = new Array();
//add event handlers to all three buttons
for(var i=1;i<=3;i++){
myClickFunctions[i]=function(){
var index = i;
alert(index);
}
var buttonID = "#butt";
var button = $(buttonID + i);
button.click(myClickFunctions[i]);
}
});
Every button prints 4. Why is this and what is a good way to make each one print the value of i in which the handler was created?
Read up on JavaScript closures and how they work. The fact is the
iinbutton.click(myClickFunctions[i]);at the bottom will be 4 at the end. Remember the that var index=i isn’t set when the function is declared, only when it is called. What you need to do is wrap the function in a closure like so:or better yet, do this:
The myClickFunctions function will take the present value of i, and return a function with that value already set. That is the proper way to do this.