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.