2017-02-10 2 views
2

Я хочу добавить td с помощью массива и ниже - данный образец. Как я могу заполнить тег <tr> с полными деталями, доступными в массиве.Вставка данных строк таблицы с помощью jquery

$(document).ready(function() { 
 
     $('#myTable > tbody:last-child').append('<tr><td>8:30am</td></tr>'); 
 
var timing = ['14:30' , '21:00']; 
 
    $.each(timing,function(i,v){ 
 
    //how can i enter the remaining data using array to complete the <tr> tag 
 
    }) 
 
} 
 
       
<table id="myTable" class="table"> 
 
         <thead> 
 
          <tr> 
 
           <th>Morning</th> 
 
           <th>Afternoon</th> 
 
           <th>Evening</th> 
 
           </tr> 
 
          </thead> 
 
         <tbody> 
 
          <tr id="months_row"> 
 
           
 
          </tr> 
 
         
 
         </tbody> 
 
        </table>

ответ

1

Используйте Array#map метод для создания tr элементов и добавить его к ранее созданному tr.

$(document).ready(function() { 
 
    $('#myTable > tbody:last-child').append(
 
    // wrap to make it jQuery object 
 
    $('<tr><td>8:30am</td></tr>') 
 
    // append the td's to the tr 
 
    .append(
 
     // generate the td's array 
 
     ['14:30', '21:00'].map(function(v) { 
 
     // generate td with the text 
 
     return $('<td>', { 
 
      text: v 
 
     }); 
 
     }) 
 
    ) 
 
) 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table id="myTable" class="table"> 
 
    <thead> 
 
    <tr> 
 
     <th>Morning</th> 
 
     <th>Afternoon</th> 
 
     <th>Evening</th> 
 
    </tr> 
 
    </thead> 
 
    <tbody> 
 
    <tr id="months_row"> 
 

 
    </tr> 
 

 
    </tbody> 
 
</table>


Или генерации HTML-строку, добавляемых.

$(document).ready(function() { 
 
    $('#myTable > tbody:last-child').append(
 
    '<tr><td>8:30am</td>' + ['14:30', '21:00'].map(function(v) { 
 
     return '<td>' + v + '</td>' 
 
    }).join('') + '</tr>' 
 
) 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table id="myTable" class="table"> 
 
    <thead> 
 
    <tr> 
 
     <th>Morning</th> 
 
     <th>Afternoon</th> 
 
     <th>Evening</th> 
 
    </tr> 
 
    </thead> 
 
    <tbody> 
 
    <tr id="months_row"> 
 

 
    </tr> 
 

 
    </tbody> 
 
</table>

+0

я хочу, чтобы добавить все данные в одном тега, так что таблица будет в комплекте с равными строками и coloums.can вы? – muther

+0

@muther: обновлено –

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