user1173536 user1173536 - 5 months ago 9
Javascript Question

JavaScript class & jQuery loop variable reference

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

Answer

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);
            });
        })();
    }    
}
Comments