javascript - Appending elements to a parent element inside arr.each loop
问题描述
I am writing a loop that will append a child div to a parent div based on each element from an array. I have attempted to create a parent element and append child nodes to the parent. My thought is I can iterate over an array and for each element I can append a new child element.
function createHtmlChildElems(arr){
var list= document.createElement('div');
var item= document.createElement('div');
list.innerHTML = '';
//iterate over my array and append something for each element in the array
$.each(arr, function(index,element){
item.innerHTML=`index: ${index}`
list.appendChild(item);
});
return list;
}
List returns only the parent element that contains one childnode. For example, if passing in a three element array, I would expect the result to include 'index: 0' 'index: 1' 'index: 2'
but it only contains 'index: 2'
解决方案
问题是因为您声明了一个item
div,并在每次迭代中更新它。要附加多个元素,您需要div
在循环中创建新实例:
function createHtmlChildElems(arr) {
var list = document.createElement('div');
list.innerHTML = '';
arr.forEach(function(element, index) {
var item = document.createElement('div');
item.innerHTML = `index: ${index}`
list.appendChild(item);
});
return list;
}
var foo = ['a', 'b', 'c'];
var elems = createHtmlChildElems(foo);
document.querySelector('div').append(elems);
<div></div>
请注意,我将$.each()
调用更改为普通调用,forEach()
因此您不需要 jQuery 依赖项。
推荐阅读
- reactjs - 警告:React 无法识别 DOM 元素上的 `FirstName` 属性
- gpu - 如何使用 Gstreamer 测试基于位融合的 GPU
- sql - 如何根据最大值和最小值将一组 SQL 记录转换为单行?
- javascript - 语法错误:编译 ejs 时出现意外标记“else”
- postgresql - 我们可以从 Postgres 表创建 Flink DataStream
- scala - 类型与值字段不匹配的值类和导入的猫的任一语法
- java - 如何添加队列服务来存储日志并在任务完成时通知?
- java - 如何在 java 8 中使用 Optionals 编写代码
- wcf - 使用 BizTalk WCF 服务发布向导的架构中的枚举?
- python - 在beautifulsoup 中摆脱