I would like to use the click() function of jQuery within a for loop in order to make three HTML elements clickable. I created a simple test case:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js" />
<script type="text/javascript">
$(window).load(function() {
function loadContent(){
var values = ['a','b','c'];
for (var i = 0; i < values.length; ++i) {
var id = values[i];
alert(id);
$('#' + id).click(function() {
function2(id);
});
}
}
function function2(id) {
// do some fancy stuff like...
alert(id);
}
loadContent();
});
</script>
</head>
<body>
<div id="map">
<a id="a">a</a>
<a id="b">b</a>
<a id="c">c</a>
</map>
</body>
As you can see, I would like to display the character 'a' if I click on 'a' (a), display 'b' while clicking on 'b', and so on. Unfortunately, the character 'c' is displayed while clicking on 'a'. No other events are triggered. I do not see the mistake I commit.
I don't bother if this code is efficient or not. I just want to know, why click() does not act as expected in this context. Thanks in advance for any hints or solution.
Each one of the "click" handlers you create will reference that same, single variable "id". You'll note that it changes on each iteration of the loop. When the loop is done, it'll be pointing at the very last one.
You need to set up the handlers differently:
for (var i = 0; i < values.length; ++i) {
var id = values[i];
alert(id);
$('#' + id).click((function(id) {
return function() { function2(id); };
})());
}
The block constructed for your for loop does not create a new lexical scope, as it does in some languages. In Javascript, that "id" variable is a local variable to the "loadContent" function. Each one of the "click" handlers in your version references that same variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With