0

I have something like this:

var a = {
     generateDynamicStuff: function(data) {
           for(var i=0;i<data.length;i++) {
              var dyn_div = document.createElement('div');
              dyn_div.className = "dyn_div_"+data[i].name;
              dyn_div.textContent = data[i].name;
              document.getElementByClassName("dyn_list")[0].appendChild(dyn_div);

              $(document).on("click", ".dyn_div_"+data[i].name, function() { alert(i); a.otherFunction(i);});
           }
     },

     otherFunction: function(some_index) {....}
}

The idea is, I am given a list of names which I will generate clickable div elements with. When one of these divs are clicked, its index will be passed to otherFunction().

The problem is, function() { alert(i); a.otherFunction(i);} always gives the last index. That is, if I have 5 items, then i in the anonymous function is always giving me "4" no matter which div I am clicking.

Why is this?

3

2 Answers 2

1

here is the scope problem here click event just binds the function not execute at binding time it executes when actually event occurs at that time it takes the last value of 'i' so you can try this

var a = {
 generateDynamicStuff: function(data) {
       for(var i=0;i<data.length;i++) {
          var dyn_div = document.createElement('div');
          dyn_div.className = "dyn_div_"+data[i].name;
          dyn_div.textContent = data[i].name;
          dyn_div.setAttribute("index", i);
          document.getElementByClassName("dyn_list")[0].appendChild(dyn_div);

          $(document).on("click", ".dyn_div_"+data[i].name, function(e) { 
               var index = $(this).attr("index");
               alert(index); 
               a.otherFunction(index);
          });
       }
 },

 otherFunction: function(some_index) {....}
}
Sign up to request clarification or add additional context in comments.

Comments

0

It is the classic closure variable in a loop issue

var a = {
    generateDynamicStuff: function (data) {
        var $ct = $('.dyn_list');
        $.each(data, function (i, data) {
            $('<div />', {
                'class': "dyn_div_" + data.name,
                text: data.name
            }).appendTo($ct).on('click', function () {
                alert(i);
                a.otherFunction(i);
            })
        })
    },

    otherFunction: function (some_index) {....
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.