我想根据分配的数组创建一个动态表,如下图:
我的代码:
的HTML
<table id="selectTable" class="m-table">
<thead>
<tr>
<th>Products</th>
<th>Range</th>
</tr>
</thead>
</table>
JQUERY
function drawTable(data) {
var dateTable = $('#selectTable');
selectEl = $('<select>'),
selectVal = [
{val : 1, text: '1'},
{val : 2, text: '2'},
{val : 3, text: '3'},
{val : 4, text: '4'},
{val : 5, text: '5'}
];
$(selectVal).each(function() {
selectEl
.append($('<option>')
.attr('value',this.val)
.text(this.text));
});
dateTable.children('tbody').empty();
$.each(data,function(k,v){
var row = $('<tr />',{'class':'row-'+k});
dateTable.append(row);
row.append($('<td />').append(v));
row.append($('<td />').append(selectEl + ' ' + selectEl ));
});
}
var a = ['Product-1','Product-2','Product-3','Product-4','Product-5'];
drawTable(a);
Table和selectbox将动态创建并追加到表的每一行。我怎样才能做到这一点?
http://jsfiddle.net/dsjLT/2/
最佳答案
不确定您可以那种方式重用selectEl。我会尝试为每一行重新创建它。这有效(尽管需要清除):
function drawTable(data) {
var dateTable = $('#selectTable');
dateTable.children('tbody').empty();
$.each(data,function(k,v){
var selectEl = $('<select>'),
selectVal = [
{val : 1, text: '1'},
{val : 2, text: '2'},
{val : 3, text: '3'},
{val : 4, text: '4'},
{val : 5, text: '5'}
];
$(selectVal).each(function() {
selectEl
.append($('<option>')
.attr('value',this.val)
.text(this.text));
});
var row = $('<tr />',{'class':'row-'+k});
dateTable.append(row);
row.append($('<td />').append(v));
row.append($('<td />').append(selectEl));
});
}
var a = ['Product-1','Product-2','Product-3','Product-4','Product-5'];
drawTable(a);