0

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.

http://jsfiddle.net/2f9qq931/

<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?

discardthis
  • 169
  • 1
  • 6
  • 14
  • Related: http://stackoverflow.com/questions/111102/how-do-javascript-closures-work – blgt Jan 26 '15 at 16:29
  • 1
    All your handlers are sharing the same `item`variable, which by the time they are called have the last value. See the linked question and http://jsfiddle.net/mendesjuan/2f9qq931/2/ which creates a separate variable for each handler – Ruan Mendes Jan 26 '15 at 16:30
  • Thanks for your help; I'll mark this as answered when I figure how to do that... – discardthis Jan 26 '15 at 16:37
  • 1
    I think a better description of the issue is contained in this article: http://dmitrysoshnikov.com/ecmascript/javascript-the-core/ - the section on closures will explain the issues. You'll need an immediate function like this: for (item in list) { (function(item){ var clickable = document.createElement("div"); clickable.innerHTML = list[item]; clickable.onclick = function() { subFunction(item); } container.appendChild(clickable); })(item); } – nril Jan 26 '15 at 17:01

0 Answers0