首页 > 解决方案 > 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'

标签: javascriptjquery

解决方案


问题是因为您声明了一个itemdiv,并在每次迭代中更新它。要附加多个元素,您需要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 依赖项。


推荐阅读