动态创建元素并添加 onclick 事件不起作用 [英] Dynamically creating elements and adding onclick event not working

查看:48
本文介绍了动态创建元素并添加 onclick 事件不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 for 循环,它创建 div 元素,ID 为category1"、category2"等.循环遍历键/值数组,如下所示:

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:

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

因此,div 的 ID 是类别"+ 键.

So, the IDs of the divs are 'category' + the key.

在将元素添加到容器 div 的 innerHTML 的 for 循环中,我添加了一个 onclick 事件.

Within the for-loop where the elements are added to the innerHTML of a container-div, I add an onclick-event.

这就是我所说的 for 循环:

This is the for-loop that 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]); }
}

其中 categories 是上面的数组.

where categories is the above array.

问题是,onclick 仅适用于数组中的最后一个元素.如果我使用 Safari 调试器检查并输入category3.onclick",它会显示为空.如果我输入category4.onclick"(这是最后一个),它会返回正确的函数.

The problem is, the onclick is only working for the LAST element in the array. If I check with the Safari-debugger and type "category3.onclick" it says null. If I type "category4.onclick" (which is the last one) it returns the correct function.

这怎么可能?以及如何解决?

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. 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);

这篇关于动态创建元素并添加 onclick 事件不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆