I am new to javascript. I am trying to add "click" eventlistener to <div>
elements in the cycle, which are nested in the parent <div>
element (id="cont").
But the problem is, that if I pass argument cont.children[i]
in the "ClickOnMe" function, the reference points to the cont.children[cont.length]
after completition of the cycle (which does not exist in reality). Here is the problematic piece of code:
cont.children[i].addEventListener("click", function() {ClickOnMe(cont.children[i]);});
Passing constant 0
instead of i
variable is the only way, how to make it "work":
cont.children[i].addEventListener("click", function() {ClickOnMe(cont.children[0]);});
But it fix only specific code below, what is obviously non-sense in the other case. May somebody tell me, how to correct it?
here is example. Clicking on the text "I am Anna" throws an exception:
<!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>Problem</title>
</head>
<script>
var girlFriend;
var cont;
function ClickOnMe(sender){
alert(sender.innerHTML);
}
function init(){
cont = document.getElementById("container");
for (i=0; i < cont.children.length; i++){
var el = cont.children[i];
var elid = el.attributes.getNamedItem("id").value;
switch (elid) {
case "anna":
cont.children[i].addEventListener("click", function() {ClickOnMe(cont.children[i]);}); // looses reference
// cont.children[i].addEventListener("click", function() {ClickOnMe(cont.children[0]);}); // this works
break;
case "betty":
girlFriend = el;
el.addEventListener("click", function() {ClickOnMe(girlFriend);}); // works well
break;
}
}
}
</script>
<body onload="init()">
<div id="container">
<div id="anna">I am Anna </div>
<div id="betty">I am Betty </div>
</div>
</body>
</html>