问题
I have a standard table structure like this:
<table id="test">
<th>...</th>
<tr><td>one thing</td></tr>
<tr><td>another</td></tr>
...
...
</table>
I know how to clone the entire table, or the nth row of a table, but what I need is the whole thing, EXCEPT the 2nd, 3rd, 4th etc row of the table, in other words:
<table id="test">
<th>...</th>
<tr><td>one thing</td></tr>
</table>
Ideas please?
回答1:
"I know how to clone the entire table..."
Then do that, clone the entire table, then remove what you dont need.
A trick to select everything except first child is to use *+*
. +
selector in css mean the matching element on right side next to the element on the left side.
In the end, you can use that :
var $clone = $('#test').clone().find('tr+tr').remove().end();
$clone
will then be your clone table with only the first row.
回答2:
Another solution is to use the following child filter selector: :not(:first-child)
. But you have plenty other solutions combining all these selectors.
var $clone = $("#test").clone();
$clone.find("tr:not(:first-child)").remove();
$("#target").html($clone);
Example: http://jsfiddle.net/rnogdu0L/
$("#but").click(function() {
var $clone = $("#test").clone();
$clone.find("tr:not(:first-child)").remove();
$("#target").html($clone);
});
td {
border: 1px solid blue;
}
#source {
min-height: 20px;
background: pink;
}
#target {
min-height: 20px;
background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="source">
<table id="test">
<th>do not delete this</th>
<tr><td>one thing</td></tr>
<tr><td>another</td></tr>
</table>
</div>
<div id="target">
</div>
<button id="but">Clone & Delete</button>
来源:https://stackoverflow.com/questions/28486026/jquery-cloning-a-table-and-its-first-row