Dynamically create items and add inactive onclick events

I have a for loop that creates div-elements with identifiers like 'category1', 'category2', etc. The loop goes through the key / value array, which looks something like this:

"0" : "Java",
"1" : "JavaScript",
"2" : "HTML"

So divs ids are a "category" + key.

Inside the for loop, where elements are added to the innerHTMLcontainer div, I add onclick-event.

This is for the loop I'm talking about:

for (var key in categories) {
    categoriesBlock.innerHTML += '<div class="category" id="category' + key + '">' + categories[key] + '</div>';

    document.getElementById('category' + key).onclick = function() { showPostsForCategory(key, categories[key]); }
}

where categoriesis the array indicated above.

, onclick LAST . Safari- "category3.onclick", null. "category4.onclick" ( ), .

? ?

+4
1

. , , , . .

for (var key in categories) {        
    (function(){
      var _key = key;
      document.getElementById('category' + _key).onclick = function() { showPostsForCategory(_key, categories[_key]); }
    })();
}

...

, html. html.

var div = document.createElement('div');
div.onclick = function(){...};
categoriesBlock.appendChild(div);
+2

All Articles