i have data which i loop and build dynamically HTML label elements to each element, i attach addEventListener with click event and function that takes the current value.
but when i click the elements that are created only the last element from the initial array is passed as an argument to the addEventListener function.
in the below example when clicking on foo1 or foo2 the value is always of foo3
i expect that each onclick hold its own key data.
so when i click foo1 it will give foo1
and when i click foo2 it will give foo2
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="UTF-8">
<title>Title</title>
<style>
</style>
<script>
var data = {
"foo1" : "aaa",
"foo2" : "bbb",
"foo3" : "ccc"
}
var popolateDS = function() {
self = this;
for(var key in data) {
if (data.hasOwnProperty(key)) {
var label = document.createElement('label');
label.innerHTML = key;
label.id = "lbl_"+key;
label.addEventListener("click", () =>{
self.dsOnClick(key);
}, false);
document.getElementById("container2").appendChild(label);
var br = document.createElement('br');
document.getElementById("container2").appendChild(br);
}
}
}
var dsOnClick = function(key) {
alert(key);
}
</script>
</head>
<body>
<div id="container2">
</div>
<button onclick="popolateDS()">click</button>
</body>
</html>