I have a table similar to the following.
<table class="schedule-table" cellspacing="1" border="0" style="width:100%;">
<tr class="DataRow" id="DataRow_1">
<td class="resource" style="display:none;">8</td>
<td class="resource">John Smith</td>
<td class="resource">blah blah blah</td>
<td class="resource">blah blah blah</td>
<td class="resource">blah blah blah</td>开发者_如何转开发
<td class="resource">blah blah blah</td>
</tr>
<tr class="DataRow" id="DataRow_2">
<td class="resource" style="display:none;">9</td>
<td class="resource">Huck Fin</td>
<td class="resource">blah blah blah</td>
<td class="resource">blah blah blah</td>
<td class="resource">blah blah blah</td>
<td class="resource">blah blah blah</td>
</tr>
<tr class="DataRow" id="DataRow_3">
<td class="resource" style="display:none;">10</td>
<td class="resource">Tom Sawyer</td>
<td class="resource">blah blah blah</td>
<td class="resource">blah blah blah</td>
<td class="resource">blah blah blah</td>
<td class="resource">blah blah blah</td>
</tr>
</table>
I'd like to select #DataRow_2 and replace the 4th and 5th cells with :
var newTd = <td class="newclass" colspan="2">Stuff for cell that should span two cells</td>
How can I accomplish this?
This should get you started:
$(document).ready(function(){
var $row = $("#DataRow_2").find(".resource");
$($row[4]).remove();
$($row[3]).replaceWith($("<td class='newclass' colspan='2'>Stuff for cell</td>"));
});
I assume you have a broader use case so you'll want to make a function and pass in the cells to remove, replace, etc.
You can play with the JSfiddle here:http://jsfiddle.net/UV2Ce/
var $dt=$('#DataRow_2');
$('td', $dt).slice(-2).remove();
$dt.append('<td class="newclass" colspan="2">Stuff for cell that should span two cells</td>');
First line: Saves a jQuery object containing #DataRow_2. We will use this later.
Second line: Searches for tds in the context of #DataRow_2, slicing only the last two ones (4., 5.) and removing them.
Third line: Appends the new td to #DataRow_2
UPDATE: If you need to cut off different cells, please refer to the slice() Manual Page. slice(-2)
will get the last two elements, if you need explicitly the 4. and 5. you can write slice(3,5)
.
As simple as this:
$('#DataRow_2 td:gt(3)')
.wrapAll('<td class="newclass" colspan="2">Stuff for cell that should span two cells</td>')
.remove();
Can simply be done in one line:
$("#DataRow_2").find("td:gt(3)").remove().end().append(newTd);
Query for the row, and then find any td greater :gt() than index 3. Call end()
to get back to the initial query of #DataRow_2
and than append your <td/>
to that row.
Example on jsfiddle.
var newTd = <td class="newclass" colspan="2">Stuff for cell</td>
jQuery('#DataRow_2').find('td:last').remove().end().find('td:last').replaceWith(newTd);
Use either the eq or nth-child selector.
精彩评论