我想使用 Javascript 将整个表分成三个子表。每个表都应保留其标题信息。
我无法调整 ID 或类,因为它们是由 Web 应用程序生成的,因此我需要使用可用的资源。
我已经尝试用 Jfiddle 破解这个问题有一段时间了,但我感到很沮丧。我对 Javascript 还很陌生,但无法想象这需要大量代码。如果有人知道如何按行大小将其分开(即拆分表,但有选择地),那也将不胜感激。
我仅限于 Javascript 和 Jquery 1.7。
<div id="serviceArray">
<table border="1" class="array vertical-array">
<thead>
<tr>
<th>#</th>
<th>Savings</th>
<th>Expenses</th>
<th>Savings</th>
<th>Expenses</th>
<th>Savings</th>
<th>Expenses</th>
</tr>
</thead>
<tbody>
<tr>
<td>Sum</td>
<td>$180</td>
<td>$500</td>
<td>$300</td>
<td>$700</td>
<td>$600</td>
<td>$1000</td>
</tr>
<tr>
<td>Home</td>
<td>$100</td>
<td>$200</td>
<td>$200</td>
<td>$300</td>
<td>$400</td>
<td>$500</td>
</tr>
<tr>
<td>Work</td>
<td>$80</td>
<td>$300</td>
<td>$100</td>
<td>$400</td>
<td>$200</td>
<td>$500</td>
</tr>
</tbody>
</table>
</div>
最佳答案
你的意思是这样吗?
var tables = $('#serviceArray table tbody tr').map(function () { //For each row
var $els = $(this).closest('tbody') //go to its parent tbody
.siblings('thead').add( //fetch thead
$(this) //and add itself (tr)
.wrap($('<tbody/>')) //wrapping itself in tbody
.closest('tbody')); //get itself with its tbody wrapper
return $els.clone() //clone the above created steps , i.e thead and tbody with one tr
.wrapAll($('<table/>', { //wrap them all to a new table with
'border': '1', //attributes.
'class': 'array vertical-array'
})
).closest('table'); //get the new table
}).get();
$('#serviceArray table').remove();
$('body').append(tables); //append all to the table.
<强> Demo
或者只是简单地克隆该表并从 tbody 中删除除此之外的所有其他 tr,并将其添加到 DOM(更短的解决方案)。
var tables = $('#serviceArray table tbody tr').map(function (idx) {
var $table = $(this).closest('table').clone().find('tbody tr:not(:eq(' + idx + '))').remove().end();
return $table;
}).get();
<强> Demo
所使用的每种方法都在网络上提供了文档,您可以使用它来自行解决您需要的问题。
关于javascript - 使用 Javascript 将表拆分为一行的单独表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19329919/