jQuery how to wrap a table cell
I'd to add a wrapper around a row with jquery. I've made several attempts but am not able to. I'm only able via have a html template and filling in but doing orig.html() I lose any input selections values that were there.
Original html:
<table><tbody>
<tr id="myitem1"><td>I need a coat1</td></tr>
<tr id="myitem2"><td>I need a coat2</td></tr></tbody></table>
=== I want to use jQuery to wrap the rows and add a button cell and get a result of:
<table><tbody>
<tr id="myitem1">
<td>
<table><tbody>
<tr><td>I need a coat1</td></tr>
</tbody></table>
</td>
<td><input type="button" value="click1"></td>开发者_JS百科;
</tr>
<tr id="myitem2">
<td>
<table><tbody>
<tr><td>I need a coat2</td></tr>
</tbody></table>
</td>
<td><input type="button" value="click1"></td>
<tr>
</tbody></table>
I'm assuming that you want to take all the columns in each row, wrap them into a table inside a single column and then add a column to the row.
$('tr').each( function() {
$(this).children().wrapAll('<td><table><tr></tr></table></td>');
$(this).append('<td><input type="button" value="click1"></td>');
});
<script>
$(function(){
var flowbox_table = $('img.flowbox').wrap('<table />');
var flowbox_tr = $(flowbox_table).wrap('<tr />');
var flowbox_td = $(flowbox_tr).wrap('<td />');
});
</script>
Use tr[id^='myitem']
to select it.
The selector <tag>[<attr>^='<prefix>'] selects all elements of the tag
with attribute attr
that starts with the prefix
.
Here is the whole code:
<html>
<head>
<script src="jquery.js" type="text/javascript"></script>
<script>
function template(pStr, pAttrs) {
return pStr.replace(/{\$([^}]*)\$}/g, function (a, pName) {
return pAttrs[pName];
});
}
const TDReplaceTemplate =
" <td>" + "\n" +
" <table><tbody>" + "\n" +
" <tr>{$OrgTD$}</tr>" + "\n" +
" </tbody></table>" + "\n" +
" </td>" + "\n" +
" <td><input type=\"button\" value=\"click1\"></td>" + "\n";
$(document).ready(function() {
$("tr[id^='myitem']").each(function(aTR) {
const aOrgTD = $(this).html();
const aNewTD = template(TDReplaceTemplate, { OrgTD: aOrgTD } );
$(this).html(aNewTD);
});
});
</script>
</head>
<body>
<table><tbody>
<tr id="myitem1"><td>I need a coat1</td></tr>
<tr id="myitem2"><td>I need a coat2</td></tr>
</tbody></table>
</body>
</html>
Hope this helps.
精彩评论