且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-02 14:40:58

这是范围界定的问题.单击处理程序指向最后一个值,因为这就是循环结束时的结果.这是一种捕获值的方法.

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

编辑...

此外,字符串连接不是创建 html 元素的理想方式.在某些浏览器中,插入文本和它成为实际的 html 元素之间可能存在延迟.

Also, string concatenation is not the ideal way to create html elements. In some browsers, there might be a delay between when you insert text, and when it becomes an actual html element.

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