我正在尝试添加/删除表行。
这是我的代码:
HTML表格
<div id="POItablediv"> <input type="button" id="addPOIbutton" value="Add POIs"/><br/><br/> <table id="POITable" border="1"> <tr> <td>POI</td> <td>Latitude</td> <td>Longitude</td> <td>Delete?</td> <td>Add Rows?</td> </tr> <tr> <td>1</td> <td><input size=25 type="text" id="latbox" readonly=true/></td> <td><input size=25 type="text" id="lngbox" readonly=true/></td> <td><input type="button" id="delPOIbutton" value="Delete" onclick="deleteRow(this)"/></td> <td><input type="button" id="addmorePOIbutton" value="Add More POIs" onclick="insRow()"/></td> </tr> </table> </div>
JavaScript
function deleteRow(row) { var i=row.parentNode.parentNode.rowIndex; document.getElementById('POITable').deleteRow(i); } function insRow() { var x=document.getElementById('POITable').insertRow(1); var c1=x.insertCell(0); var c2=x.insertCell(1); c1.innerHTML="NEW CELL1"; c2.innerHTML="NEW CELL2"; }
现在,如您所见,在我的表格中,我有文本字段和按钮。我想要的是:
仅重复行的结构。我现在无法执行此操作,因为innerHTM仅接收文本。如何插入文本框或标签?
文本字段的ID也应该不同,因为稍后我将检索这些值以将其放入数据库中。
我想放置一个函数以增加POI的数量
有人可以帮我吗?
您可以仅克隆具有输入的第一行,然后获取嵌套的输入并更新其ID以添加行号(并与第一单元格相同)。
function deleteRow(row) { var i=row.parentNode.parentNode.rowIndex; document.getElementById('POITable').deleteRow(i); } function insRow() { var x=document.getElementById('POITable'); // deep clone the targeted row var new_row = x.rows[1].cloneNode(true); // get the total number of rows var len = x.rows.length; // set the innerHTML of the first row new_row.cells[0].innerHTML = len; // grab the input from the first cell and update its ID and value var inp1 = new_row.cells[1].getElementsByTagName('input')[0]; inp1.id += len; inp1.value = ''; // grab the input from the first cell and update its ID and value var inp2 = new_row.cells[2].getElementsByTagName('input')[0]; inp2.id += len; inp2.value = ''; // append the new row to the table x.appendChild( new_row ); }
下面的演示
function deleteRow(row) { var i = row.parentNode.parentNode.rowIndex; document.getElementById('POITable').deleteRow(i); } function insRow() { console.log('hi'); var x = document.getElementById('POITable'); var new_row = x.rows[1].cloneNode(true); var len = x.rows.length; new_row.cells[0].innerHTML = len; var inp1 = new_row.cells[1].getElementsByTagName('input')[0]; inp1.id += len; inp1.value = ''; var inp2 = new_row.cells[2].getElementsByTagName('input')[0]; inp2.id += len; inp2.value = ''; x.appendChild(new_row); } <div id="POItablediv"> <input type="button" id="addPOIbutton" value="Add POIs" /><br/><br/> <table id="POITable" border="1"> <tr> <td>POI</td> <td>Latitude</td> <td>Longitude</td> <td>Delete?</td> <td>Add Rows?</td> </tr> <tr> <td>1</td> <td><input size=25 type="text" id="latbox" /></td> <td><input size=25 type="text" id="lngbox" readonly=true/></td> <td><input type="button" id="delPOIbutton" value="Delete" onclick="deleteRow(this)" /></td> <td><input type="button" id="addmorePOIbutton" value="Add More POIs" onclick="insRow()" /></td> </tr> </table>