使用JQuery从数组填充表

我有一个16个元素的数组,我想填充一个表。 我希望它有2行,每行有8个单元格,用数组填充。 我的问题是,当填充表时,表将所有元素填充到一行。 我没有太多使用JQuery的经验,我想尝试让它工作。 任何帮助表示赞赏! 这是我的代码:

//**********Javascript & JQuery********** var array = [1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8]; var count = 0; var totalCells = 8; function writeTable() { var $table = $('#summaryOfResults'); //Array always includes enough elements to fill an entire row, which is 8 cells. Outer loop determines how many rows to make. //Inner loop determines the elements to print in the cells for that row. for (var i = 0; i < array.length / 8; i++) { $table.find('#body').append(''); for (var j = 0; j < totalCells; j++) { $table.append('' + array[count] + ''); count++; } $table.append(''); } } //**********HTML**********     
# ni nf Ei (J) Ef (J) ΔE (J) ΔE (kJ/mol) λ (nm)

首先,您必须重置每次点击的count
接下来,您必须指定必须附加到

元素的确切位置。 至于现在,你将它们直接附加到

 // your declaration of the table element: var $table = $('#summaryOfResults'); // ... // then in nested loop, you're appending the cells directly to the table: $table.append('' + array[count] + ''); 

最后一件事 – .append('')不是创建元素对象的正确方法,它应该是'

''

'


这应该是你正在寻找的:

 function writeTable() { // cache  element: var tbody = $('#body'); for (var i = 0; i < array.length / 8; i++) { // create an  element, append it to the  and cache it as a variable: var tr = $('').appendTo(tbody); for (var j = 0; j < totalCells; j++) { // append  elements to previously created  element: tr.append('' + array[count] + ''); count++; } } // reset the count: count = 0; } 

的jsfiddle


或者,创建一个HTML字符串并将其附加到循环外的表中:

 function writeTable() { // declare html variable (a string holder): var html = ''; for (var i = 0; i < array.length / 8; i++) { // add opening  tag to the string: html += ''; for (var j = 0; j < totalCells; j++) { // add  elements to the string: html += '' + array[count] + ''; count++; } // add closing  tag to the string: html += ''; } //append created html to the table body: $('#body').append(html); // reset the count: count = 0; } 

的jsfiddle