I've read posts that detail how to use onclick = function(){};
to dynamically generate onclick events.
However, I cannot figure out how to successfully pass arguments to a function within this anonymous onclick function.
<div id="container"></div>
<script>
function subFunction(arg) {
console.log(arg);
}
function myFunction() {
var container = document.getElementById("container");
var list = {
"one": "cat",
"two": "dog",
"three": "fish"
};
for (item in list) {
var clickable = document.createElement("div");
clickable.innerHTML = list[item];
clickable.onclick = function() {
subFunction(item);
}
container.appendChild(clickable);
}
}
myFunction();
</script>
This should give me
<div>cat</div>
<div>dog</div>
<div>fish</div>
And upon clicking each div, the console will log one
two
and three
...but the console is only logging three
. How do I get subFunction
to correctly log the object properties?