Javascript-获取子元素innerHTML onclick
我正在包装器标记中创建许多子元素:Javascript-获取子元素innerHTML onclick,javascript,appendchild,Javascript,Appendchild,我正在包装器标记中创建许多子元素: // display prompts in html function show_prompts(found_elements){ var div = document.getElementById("prompts"); // iterate through list of found words for (var i=0; i < found_elements.len
// display prompts in html
function show_prompts(found_elements){
var div = document.getElementById("prompts");
// iterate through list of found words
for (var i=0; i < found_elements.length; i++){
// initialize child element
var p = document.createElement('p');
// creating specific ID for each child
identificator = 'variant'+[i];
p.id = identificator;
// filling child with text
p.innerHTML = found_elements[i];
p.addEventListener("click", function(){choose_prompt(identificator);});
//p.setAttribute("onclick", "choose_prompt()");
div.appendChild(p);
}
}
目标是:
单击浏览器中的一个子元素后,函数choose\u prompt将激活,并使用所单击元素的innerHTML进行一些工作
问题是:
单击时,选择提示确定所有元素的最后一次迭代id。我知道这是因为addEventListener是在循环中调用的
问题:
当单击确切的子元素时,如何传递正确的id以选择提示
我被期望在没有任何jquery的情况下处理任务。
我在JS的第二天,所以不要太严格
非常感谢您的帮助。谢谢 JS没有块作用域,因此所有identificator绑定实际上是最后更新的值 使用函数调用将其包装,以创建独立的闭包:
for (var i=0; i < found_elements.length; i++) {
(function(i) {
// do your job here with i
})(i)
}
注意:对于第二种方法,如果found_元素由domapi querySelectorAll、getElementsByTagName或其他类似方法返回,则它不是一个真正的数组。然后您应该对其调用数组方法:
Array.prototype.forEach.call(found_elements, function(element, i) {
// do your job here with i
});
谢谢!花足够的时间在这上面,嗯。这就解决了问题
Array.prototype.forEach.call(found_elements, function(element, i) {
// do your job here with i
});