2015-03-28 5 views
1

У меня есть массив из 16 элементов, которые я хочу заполнить таблицей. Я хочу, чтобы у него было 2 строки с 8 ячейками в каждой строке, которые заполнены массивом. Моя проблема в том, что когда таблица заполняется, таблица заполняет все элементы в одну строку. У меня не было большого опыта работы с JQuery, и я хочу попытаться заставить это работать. Любая помощь приветствуется! Вот мой код:Заполнение таблицы из массива с помощью 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('<tr>'); 
     for (var j = 0; j < totalCells; j++) { 
      $table.append('<td>' + array[count] + '</td>'); 
      count++; 
     } 
     $table.append('</tr>'); 
    } 
} 

//**********HTML********** 
<html> 
<head> 
</head> 
<body> 
<div id="resultsTable"> 
    <table id='summaryOfResults' border='1'> 
     <tbody id="body"> 
      <tr> 
       <th>#</th> 
       <th>n<sub>i</sub></th> 
       <th>n<sub>f</sub></th> 
       <th>E<sub>i</sub> (J)</th> 
       <th>E<sub>f</sub> (J)</th> 
       <th>&Delta;E (J)</th> 
       <th>&Delta;E (kJ/mol)</th> 
       <th>&lambda; (nm)</th> 
      </tr> 
     </tbody> 
    </table> 
</div> 
<div id="tableButtons"> 
    <button id='copyButton' onclick=''>Copy Table</button> 
    <button id='clear' onclick='clearTable();'>Clear Table</button> 
    <button id='write' onclick='writeTable();'>Write Table</button> 
</div> 
</body> 
</html> 

ответ

5

Во-первых, вы должны сбросить count на каждый клик.
Далее вы должны указать, где именно должны быть добавлены элементы <td>. На данный момент, вы добавляя их непосредственно к <table>:

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

Последняя вещь - .append('</tr>') не правильный способ создания объекта элемента, он должен быть '<tr/>' или '<tr></tr>'.


Это должно быть то, что вы ищете:

function writeTable() { 
    // cache <tbody> element: 
    var tbody = $('#body'); 
    for (var i = 0; i < array.length/8; i++) { 
     // create an <tr> element, append it to the <tbody> and cache it as a variable: 
     var tr = $('<tr/>').appendTo(tbody); 
     for (var j = 0; j < totalCells; j++) { 
      // append <td> elements to previously created <tr> element: 
      tr.append('<td>' + array[count] + '</td>'); 
      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 <tr> tag to the string: 
     html += '<tr>'; 
     for (var j = 0; j < totalCells; j++) { 
      // add <td> elements to the string: 
      html += '<td>' + array[count] + '</td>'; 
      count++; 
     } 
     // add closing </tr> tag to the string: 
     html += '</tr>'; 
    } 
    //append created html to the table body: 
    $('#body').append(html); 
    // reset the count: 
    count = 0; 
} 

JSFiddle

+0

Спасибо за это! Мне нужно узнать больше о том, как добавить в jquery, не знаете, почему и как элементы TD могут быть добавлены к . Я думал, что это должно быть между открывающим тегом и закрывающим тегом. – user3786596

Смежные вопросы