How do you append rows to a table using jQuery?
嗨,我试图使用jQuery向表添加一行,但它无法正常工作。
可能是什么原因?
而且,我可以为新添加的行添加一些值吗?
这是代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <html> <head> <script type="text/javascript" src="jquery.js"> <script type="text/javascript"> $('a').click(function() { $('#myTable').childs('tr').append('<tr class="child"><td>blahblah<\/td></tr>'); }); </head> <body> Link <table id="myTable"> <tbody> <tr> <td> test </td> </tr> </tbody> </table> </body> </html> |
我假设您要将此行添加到
1 2 3 | $('a').click(function() { $('#myTable tbody').append('<tr class="child"><td>blahblah</td></tr>'); }); |
编辑:这是完整的源代码,它确实有效:(注意
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"> <script type="text/javascript"> $(document).ready(function() { $('a').click(function() { $('#myTable tbody').append('<tr class="child"><td>blahblah</td></tr>'); }); }); </head> <body> Link <table id="myTable"> <tbody> <tr> <td>test</td> </tr> </tbody> </table> </body> </html> |
以下代码有效
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <html> <head> <script type="text/javascript" src="jquery.js"> <script type="text/javascript"> function AddRow() { $('#myTable').append('<tr><td>test 2</td></tr>') } </head> <body> <input type="button" id="btnAdd" onclick="AddRow()"/> test <table id="myTable"> <tbody > <tr> <td> test </td> </tr> </tbody> </table> </body> </html> |
请注意,即使表中包含
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
and inserts it into the first in your table or wraps it into a new if one doesn't exist.