且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将对象从数组显示到HTML表中

更新时间:2022-12-15 12:37:29

在javascript中创建元素的正确方法就是这样

the right way to create an element in javascript, would be something like that

<div class="some"></div>


function addElement () { 
  // create new "p" element
  var newP = document.createElement("p"); 
  // add content --  the data you want display
  var newContent = document.createTextNode("hello, how are you?"); 

  newP.appendChild(newContent); //add content inside the element. 

  // add the element and content to DOM 
  var currentDiv = document.getElementById("some"); 
  document.body.insertBefore(newP, currentDiv); 
}
addElement();




https://developer.mozilla.org/es/docs/Web/API/Document/createElement

现在,如果我们将这些信息调整到表的上下文中,我们就可以通过这种方式来动态生成数据

Now, if we adapt that information to the context of the tables, we can do it on this way to generate the data dynamically

   arr = [
  'item 1',
  'item 2',
  'item 3',
  'item 4',
  'item 5'
         ];

function addElement () { 

arr.forEach(function(el,index,array){
  let tableRef = document.getElementById('some');

  // Insert a row at the end of the table
  let newRow = tableRef.insertRow(-1);

  // Insert a cell in the row at index 0
  let newCell = newRow.insertCell(0);

  // Append a text node to the cell
  let newText = document.createTextNode(el);
  newCell.appendChild(newText);
});

}
addElement();




https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableRowElement/insertCell

演示链接:小提琴