Javascript - 获取子元素内部 在点击时

Javascript - Get child element innerHTML onclick

本文关键字:内部 元素 获取 Javascript      更新时间:2023-09-26

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

// 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_prompt激活并使用单击元素的 innerHTML 进行一些工作。

问题:单击时,choose_prompt确定所有元素的上次迭代 id。我知道这是因为addEventListener是在循环中调用的。

问题:单击确切的子元素时如何将正确的 id 传递给choose_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
});

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

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