How do you append rows to a table using jQuery?
Hi I was trying to add a row to a table using jQuery, but it is not working.
What might be the reason?
And, can I put in some value to the newly added row..?
Here is the code:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$('a').click(function() {
$('#myTable').childs('tr').append('<tr class="child"><td>blahblah</td></tr>');
});
</script>
<title></title>
</head>
<body>
<a href="">Link</a>
<table id="myTable">
<tbody>
<tr>
<td>
test
</td>
</tr>
</tbody>
</table>
</body>
</html>
I'm assuming you want to add this row to the <tbody>
element, and simply using append()
on the <table>
will insert the <tr>
outside the <tbody>
, with perhaps undesirable results.
$('a').click(function() {
$('#myTable tbody').append('<tr class="child"><td>blahblah</td></tr>');
});
EDIT: Here is the complete source code, and it does indeed work: (Note the $(document).ready(function(){});
, which was not present before.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('a').click(function() {
$('#myTable tbody').append('<tr class="child"><td>blahblah</td></tr>');
});
});
</script>
<title></title>
</head>
<body>
<a href="javascript:void(0);">Link</a>
<table id="myTable">
<tbody>
<tr>
<td>test</td>
</tr>
</tbody>
</table>
</body>
</html>
The following code works
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function AddRow()
{
$('#myTable').append('<tr><td>test 2</td></tr>')
}
</script>
<title></title>
</head>
<body>
<input type="button" id="btnAdd" onclick="AddRow()"/>
<a href="">test</a>
<table id="myTable">
<tbody >
<tr>
<td>
test
</td>
</tr>
</tbody>
</table>
</body>
</html>
Note this will work as of jQuery 1.4 even if the table includes a <tbody>
element:
jQuery since version 1.4(?) automatically detects if the element you are trying to insert (using any of the append(), prepend(), before(), or after() methods) is a <tr>
and inserts it into the first <tbody>
in your table or wraps it into a new <tbody>
if one doesn't exist.
Maybe this is the answer you are looking for. It finds the last instance of <tr />
and appends the new row after it:
<script type="text/javascript">
$('a').click(function() {
$('#myTable tr:last').after('<tr class="child"><td>blahblah</td></tr>');
});
</script>
链接地址: http://www.djcxy.com/p/22976.html
上一篇: 在JavaScript中创建表格行的克隆并附加到表格
下一篇: 如何使用jQuery将行添加到表中?