除了整列新增,有時候我們只想為某一列補上一個新的儲存格。這時可以先透過 id 找到目標列,再呼叫該列的 insertCell 方法即可。
以下程式碼示範如何為 id 為 tr1 的列插入一個新儲存格並填入內容:
<!DOCTYPE html> <html> <head> <script> function insCell() { var x=document.getElementById('tr1').insertCell(0); x.innerHTML="The famous"; } </script> </head> <body> <table border="1"> <tr id="tr1"> <td>Peter</td> <td>Griffin</td> </tr> </table> <br> <input type="button" onclick="insCell()" value="Insert cell"> </body> </html>insertCell 的參數同樣代表插入位置,掌握後就能靈活調整列的結構。希望本文對你的 JavaScript 開發有所幫助。