能否在insertRow()函数中插入包含<input>标签的表格行?
当然可以用
insertRow()插入包含<input>标签的行! insertRow()只是帮你在表格(或tbody)里创建一个空的<tr>元素,之后你完全可以给这个行的单元格添加任何HTML元素,包括输入框。结合你给出的表格结构,这里有一个完整的可运行示例:
<table id="myJournalTable"> <thead> <tr> <th>No Account</th> <th>Deskripsi</th> <th>Debit</th> <th>Credit</th> <th>Job</th> </tr> </thead> <tbody id="tableBody"> <!-- 初始行 --> <tr> <td><input class="input-td" type="text" placeholder="No Account"></td> <td><input class="input-td" type="text" placeholder="Deskripsi"></td> <td><input class="input-td" type="number" placeholder="Debit"></td> <td><input class="input-td" type="number" placeholder="Credit"></td> <td><input class="input-td" type="text" placeholder="Job"></td> </tr> </tbody> </table> <button onclick="addNewInputRow()">添加新行</button> <script> function addNewInputRow() { // 先获取表格的tbody容器 const tbody = document.getElementById('tableBody'); // 在tbody末尾插入新行 const newRow = tbody.insertRow(); // 定义每个单元格对应的输入框配置 const inputSettings = [ { type: 'text', placeholder: 'No Account' }, { type: 'text', placeholder: 'Deskripsi' }, { type: 'number', placeholder: 'Debit' }, { type: 'number', placeholder: 'Credit' }, { type: 'text', placeholder: 'Job' } ]; // 循环创建单元格和输入框 inputSettings.forEach(setting => { const cell = newRow.insertCell(); const input = document.createElement('input'); input.className = 'input-td'; // 和现有输入框保持一致的类名 input.type = setting.type; input.placeholder = setting.placeholder; // 你还可以按需添加其他属性,比如name、value、onchange事件等 cell.appendChild(input); }); } </script>
这个示例里,点击按钮就会调用addNewInputRow()函数:先用insertRow()创建空行,再给每行生成对应数量的单元格,接着创建输入框并设置好属性,最后把输入框塞进单元格里。你完全可以根据自己的需求调整输入框的属性(比如添加验证规则、默认值),或者修改插入行的位置(比如插入到指定索引位置,insertRow(index))。
内容的提问来源于stack exchange,提问作者wildape
相关产品推荐
相关产品推荐

