我想通过使用数组添加td,下面是给定的示例。如何使用数组中提供的完整详细信息完成<tr>
标记。
$(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
})
}
&#13;
<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>
&#13;
答案 0 :(得分: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
});
})
)
)
})
&#13;
<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>
&#13;
或者通过生成要追加的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>'
)
})
&#13;
<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>
&#13;