繁体   English   中英

Javascript-获取子元素innerHTML onclick

[英]Javascript - Get child element innerHTML onclick

我在包装标签中创建了许多子元素:

// 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);
            }
    }

目标:单击浏览器中的一个子元素后,功能select_prompt激活并使用被单击元素的innerHTML进行一些工作。

问题:单击时, choose_prompt确定所有元素的最后一个迭代ID。 我知道它是因为在循环中调用了addEventListener

问题:单击确切的子元素时如何将正确的ID传递给choice_prompt

我希望没有任何jquery就能处理任务。 我在JS的第二天,所以不要严格。

将不胜感激。 谢谢!

JS没有块范围,因此所有identificator绑定实际上是最后更新的值。

使用函数调用将其包装以创建隔离的闭包:

for (var i=0; i < found_elements.length; i++) {
  (function(i) {
     // do your job here with i
  })(i)
}

或者使用forEach方法,每个迭代都有自己的范围:

found_elements.forEach(function(element, i) {
  // do your job here with i
});

注意:对于第二种方法,如果dom api返回了found_elementsquerySelectorAllgetElementsByTagName或其他类似方法),则它不是真正的数组。 然后,您应该在其上调用数组方法:

Array.prototype.forEach.call(found_elements, function(element, i) {
  // do your job here with i
});

暂无
暂无

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

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