简体   繁体   English

动态创建元素并添加onclick事件不起作用

[英]Dynamically creating elements and adding onclick event not working

I have a for loop that creates div -elements with IDs like 'category1', 'category2' etc. The loop goes through a key/value array, which looks something like this: 我有一个for循环创建div -elements,ID为'category1','category2'等。循环遍历一个键/值数组,看起来像这样:

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

So, the IDs of the divs are 'category' + the key. 所以,div的ID是'category'+ key。

Within the for-loop where the elements are added to the innerHTML of a container-div, I add an onclick -event. 在for循环中,元素被添加到container-div的innerHTML中,我添加了一个onclick -event。

This is the for-loop that I'm talking about: 这是我正在谈论的for循环:

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 categories is the above array. 其中categories是上面的数组。

The problem is, the onclick is only working for the LAST element in the array. 问题是, onclick仅适用于数组中的LAST元素。 If I check with the Safari-debugger and type "category3.onclick" it says null. 如果我检查Safari调试器并输入“category3.onclick”,则表示null。 If I type "category4.onclick" (which is the last one) it returns the correct function. 如果我输入“category4.onclick”(这是最后一个),它将返回正确的函数。

How is this possible? 这怎么可能? And how to solve it? 以及如何解决?

This is an issue with scoping. 这是范围界定的问题。 The click handler is pointing to the last value because that's what it ended up as when the loop ended. click处理程序指向最后一个值,因为它是循环结束时的结果。 Here is a way to trap the value. 这是一种捕获价值的方法。

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

Edit... 编辑...

Also, string concatenation is not the ideal way to create html elements. 此外,字符串连接不是创建html元素的理想方式。 In some browsers, there might be a delay between when you insert text, and when it becomes an actual html element. 在某些浏览器中,插入文本和成为实际的html元素之间可能会有延迟。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM