Code
function asignarEventos() {
var uno = document.getElementById("uno");
var dos = document.getElementById("dos");
var tres = document.getElementById("tres");
var arreglo = [uno, dos, tres];
for (var i = 0; i < arreglo.length; i++) {
var elemento = arreglo[i];
var texto = elemento.innerHTML.trim();
elemento.onclick = function(){
alert(texto);
};
}
}
asignarEventos();
<html>
<head>
</head>
<body>
<a id="uno">
Uno
</a>
<a id="dos">
Dos
</a>
<a id="tres">
Tres
</a>
</body>
</html>
Goal
The variable arreglo
contains a list of HTML elements, which are previously obtained using document.getElementById()
. Later I want to dynamically assign an event to the HTML element using the .onclick
property of the DOM Element.
What I want is that by clicking on any of the elements <a>
, a alert()
is displayed or a function is executed showing the text contained in them.
Problem
In this section of the code:
var elemento = arreglo[i];
var texto = elemento.innerHTML.trim();
elemento.onclick = function(){
alert(texto);
};
I get the element contained in the variable arreglo
, and later I get its value innerHTML
, that is, the text it contains, then I assign the attribute onclick
assigning an anonymous function that executes a alert()
showing the text that contains the HTML element.
But clicking on any of the elements always prints the innerHTML
of the last of the elements, in this case it is the word "three". When should be the value of each item individually.
Question
How can an event onClick()
be assigned to an element obtained with document.getElementById()
?
Note
It should be noted that the problem I must solve using pure JavaScript , it does not help to use a library like jQuery or others, because in that environment I can not use it.