I have a function in javascript like this:
<script type="text/javascript">
var lista = window.opener.document.getElementsByTagName("*");
for (var i = 0; i < lista.length; i++) {
lista[i].addEventListener ("click", function(){
console.log ("Pulsó el control #" + i + ": " + this.nodeName + " /" + this.tagName);
}
);
}
</script>
This function is in a window that runs through all the elements of its parent window to add an action dynamically. In this case, through the click
event on the elements, I want a message that says
"I pressed the control #" + number of the item in the list + etc .
The message I get, however, is always with the same number "i"
(in my case the 45). This is the output of the console:
Pulsó el control #45: TD /TD fowl:34 Pulsó el control #45: TR /TR fowl:34 Pulsó el control #45: TBODY /TBODY fowl:34 Pulsó el control #45: TABLE /TABLE fowl:34 Pulsó el control #45: CENTER /CENTER fowl:34 Pulsó el control #45: BODY /BODY fowl:34 Pulsó el control #45: HTML /HTML
If within the function I pass as parameter the "i" (lista[i].addEventListener ("click", function(i) )
, I get the following output:
Pulsó el control #[object MouseEvent]: CENTER /CENTER fowl:34 Pulsó el control #[object MouseEvent]: BODY /BODY fowl:34 Pulsó el control #[object MouseEvent]: HTML /HTML fowl:34 Pulsó el control #[object MouseEvent]: BODY /BODY fowl:34 Pulsó el control #[object MouseEvent]: HTML /HTML
1) What am I doing wrong? Why, if I do not pass parameters in the function, the variable "i"
is always worth 45
which is the number of elements in the parent page, and if I pass the "i"
as a parameter in the function, "MouseEvent"
appears?
2) How do I navigate the loop well so that each element has its own index value of the loop?