-1

I have function with loop and jQuery click function which I would like, after click, execute specific function. The a.id class is important, so like jQuery click definition. After click on element with specific id, I would like execute specific function. What can change is only function b?

var a = {

    id: { "id1": function () { console.log(1) }, "id2": function () { console.log(2) }, "id3": function () { console.log(3) } },
    b: function () {

        $this = this;

        for (v in $this.id) {

            $("#" + v).click(function () {

                $this.id[v]();

            });
        }

    }

}

After i click on element, i want see id1 = 1, id2 = 2, id3 = 3. But this code write value 3 for each element. This example is very simple. Problem is variable reference i know, but i can't find correct solution. Thanks

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
MarTic
  • 665
  • 3
  • 10
  • 27
  • 2
    Duplicate of many, many other posts. The problem is that the `for` loop has long since completed when the click handler is actually called so `v` has the terminal value of the loop. The solution is to put the click handler assignment in a function and pass `v` to the function. – jfriend00 Dec 14 '14 at 23:17
  • You're overcomplicating things. Get rid of the anonymous function, and just do this: `$("#"+v).click(this.id[v])` http://jsfiddle.net/02stc7q9/ – six fingered man Dec 14 '14 at 23:53

1 Answers1

1

Wrap it in an IFFE function. Read more about scope and IIFE's here http://benalman.com/news/2010/11/immediately-invoked-function-expression/.

I have provided a fiddle with an example related to your question: http://jsfiddle.net/rtmeo4nx/3/

function() {
    var $this = this;
    for (var v = 0; v <= 4; v++) {
        (function() {
            var i = v;
            $("#v" + i).on("click", function(e) {               
                e.stopPropagation();
                alert('hi' + i);
            });
        })();
    }    
}
TysonWolker
  • 436
  • 2
  • 9
  • thank you, but this doesn't work – MarTic Dec 14 '14 at 23:26
  • Fixed it and added an example. There is also a new feature in Ecmascript 6 coming that solves this with some syntactical sugar. Its a keyword called "let" that solves this in less lines, although browser support is not 100% right now. – TysonWolker Dec 14 '14 at 23:51
  • 1
    thans, i update you code and works, thank you! – MarTic Dec 15 '14 at 00:02