我使用$ .map函数将表成功转换为Objects。但是,我想转换<tr> to <dl> <th> to <dt> <td> to <dd>
然后将结果附加到页面&amp;最后从视图中隐藏原始表格。
注意:每个表的实际行数会有所不同。我假设网站上的所有表格都有thead
<div id="item">
<dl>
<dt>First Name:</dt>
<dd>James</dd>
<dt>Last Name:</dt>
<dd>Matman</dd>
<dt>Job Title:</dt>
<dd>Chief Sandwich Eater</dd>
</dl>
<dl>
<dt>First Name:</dt>
<dd>The</dd>
<dt>Last Name:</dt>
<dd>Tick</dd>
<dt>Job Title:</dt>
<dd>Crimefighter Sorta</dd>
</dl>
</div>
<div id="item"></div>
<table>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Job Title</th>
</tr>
</thead>
<tbody>
<tr>
<td>James</td>
<td>Matman</td>
<td>Chief Sandwich Eater</td>
</tr>
<tr>
<td>The</td>
<td>Tick</td>
<td>Crimefighter Sorta</td>
</tr>
</tbody>
</table>
var rowCount = $("tbody > tr").length;
var items = [];
var headers = [];
$("thead th").each(function() {
headers.push($(this).text());
});
var tbl = $('table tbody tr').map(function(r) {
return $(this).find('td').map(function(c) {
return {
row:r + 1,
col:c + 1,
cell: $(this).text()
}
}).get();
}).get();
console.log(tbl);
//$("#item").html(JSON.stringify(items));
答案 0 :(得分:3)
试试这个: -
//Get the template from table headers.
var template = $("<dl>");
$("table thead tr th").map(function () {
return $('<dt/>', {
text: $(this).text()
}).get();
}).appendTo(template);
//Now look through the data
$("table tbody tr").each(function () {
var newDl = template.clone(); //Clone the template
$(this).find('td').each(function (idx, ob) {
newDl.find('dt:nth-of-type(' + (idx + 1) + ')').after($('<dd/>', {
text: $(this).text()
})); //Construct the dd and find the position of dt after which this dd need to be insert, using nth-of-type.
})
$('#item').append(newDl); //append it to the div.
});
答案 1 :(得分:3)
只需对代码进行一些小修改,就可以轻松地从表中生成<dl>
列表:
jsFiddle:http://jsfiddle.net/nfnrJ/5/
// Create a list of headers
var headers = [];
$("thead th").each(function() {
headers.push($(this).text());
});
// Iterate through each table row
var tbl = $('table tbody tr').each(function(cIndex, cRow) {
// Create a new <dl> object for each row
var cDL = $('<dl></dl>');
// Iterate through each cell in the row
$(cRow).find('td').each(function(cCellIndex, cCell) {
// For each cell append the corresponding header as a <dt>
// and then append a <dd> element with the cell text
cDL.append('<dt>' + headers[cCellIndex] + ':</dt>')
.append('<dd>' + $(cCell).text() + '</dd>');
});
// Append the new <dl> list to the #item <div>
$('#item').append(cDL);
});
答案 2 :(得分:1)
这是我的方法:
var headers = []; $("thead th").each(function() {
headers.push($(this).text());
});
//get the table rows (but not the header).
$("tbody").children().each(function(index, tr){
//create a mew dl element
var $dl = $('<dl>');
//add the data from each row.
$(tr).children().each(function(index, td){
$dl.append($('<dt>').html(headers[index] + ':'));
$dl.append($('<dd>').html($(td).html()));
//append the dl element to the item div.
$dl.appendTo('#item');
});
});
//remove the table.
$('table').remove();