我想在每隔3 <tr>
周围包裹<td>
个标签。有办法吗?
HTML
<table id="tblOne">
<tbody>
<tr>
<td>text</td>
<td>text</td>
<td>text</td>
<td>text</td>
<td>text</td>
<td>text</td>
<td>text</td>
<td>text</td>
<td>text</td>
<td>text</td>
</tr>
</tbody>
</table>
我希望输出是这样的:
<table id="tblOne">
<tbody>
<tr>
<td>text</td>
<td>text</td>
<td>text</td>
</tr>
<tr>
<td>text</td>
<td>text</td>
<td>text</td>
</tr>
<tr>
<td>text</td>
<td>text</td>
<td>text</td>
</tr>
</tbody>
</table>
答案 0 :(得分:2)
var td = $("#tblOne td"); // Getting all td
td.each(function(i){ // Looping the td
if (i % 3 == 0) { // Splitting td as multiple of 3
td.slice(i, i+3).wrapAll('<tr/>') // Wrapping it inside tr
}
}).parent('tr').unwrap(); // Remove parent tr
<强> Working Demo 强>
答案 1 :(得分:1)
您可以使用JQuery .each()和.insertAfter()方法来播放HTML table
:
HTML:
<button type="button" id="insert">
Insert a TR after each third row
</button>
<button type="button" id="remove_and_re_insert">
Remove Old Trs and Re Insert a TR after each third row
</button>
<button type="button" id="remove">
Just Remove Old Trs
</button>
<table id="tblOne" border="1">
<tbody>
<tr>
<td>text</td>
<td>text</td>
</tr>
<tr>
<td>text</td>
<td>text</td>
</tr>
<tr>
<td>text</td>
<td>text</td>
</tr>
<tr>
<td>text</td>
<td>text</td>
</tr>
<tr>
<td>text</td>
<td>text</td>
</tr>
<tr>
<td>text</td>
<td>text</td>
</tr>
<tr>
<td>text</td>
<td>text</td>
</tr>
<tr>
<td>text</td>
<td>text</td>
</tr>
<tr>
<td>text</td>
<td>text</td>
</tr>
<tr>
<td>text</td>
<td>text</td>
</tr>
<tr>
<td>text</td>
<td>text</td>
</tr>
<tr>
<td>text</td>
<td>text</td>
</tr>
</tbody>
</table>
JAVASCRIPT / JQUERY:
// add click listener to button
$('#remove').click(function() {
// removing old TRs
if( $(".newTrs").length > 0 ){
$(".newTrs").remove();
alert("Old added New TRs removed");
}else{
alert("There are no old added TRs");
}
});
$('#remove_and_re_insert').click(function() {
// removing old TRs
if( $(".newTrs").length > 0 ){
$(".newTrs").remove();
alert("Old added New TRs removed");
}else{
alert("There are no old added TRs");
}
doAddTrs();
alert("New TRs inserted!");
});
$('#insert').click(function() {
doAddTrs();
});
function doAddTrs(){
// Looping Trs in the table #tblOne
$('#tblOne tbody tr').each(function(key, element) {
if( parseInt(key+1) % 3 == 0 ){
// Inserting new Custom Tr HTML
$( "<tr class='newTrs'><td>New 1</td><td>New 1</td></tr>" ).insertAfter(element);
console.log(key, element);
}
});
}