我创建了一个表格,可以通过填写表格来添加行。添加到表中的每一行,获取一个行号。现在,我想通过将行号放入另一个输入中(使用deleteRow函数)来删除特定行。
<table id="table">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Points</th>
</tr>
</table>
<form action="" id="form" name="form">
First name: <input type="text" id="fnaam"> <br>
Last name: <input type="text" id="lnaam"><br>
Points: <input type="text" id="points">
</form>
<button type="button" id="addBtn">Voeg toe</button>
Fill in row number: <input type="text" id="deleteRowInput"> <br>
<button type="button" id="deleteBtn">Delete Row</button>
这是我使用的Javascript。我创建了一个deleteRow函数,但尚无法正常工作。谢谢!
var addBtn = document.getElementById('addBtn');
var deleteBtn = document.getElementById('deleteBtn');
addBtn.onclick = addRow;
deleteBtn.onclick = deleteRow;
var rowNumber = 0;
function addRow() {
//getting data from form
var form = document.getElementById('form');
var newData = [];
for(var i = 0; i < form.length; i++) {
newData[i] = form.elements[i].value;
}
if(validateForm() == true) {
rowNumber++;
//Put data in table
var table = document.getElementById('table');
var newRow = table.insertRow();
//Adding rownumber to row
newRow.innerHTML = `<tr><td><i>${rowNumber}</i></td><tr>`;
for(var i = 0; i < 3; i++) {
var newCell = newRow.insertCell(i);
newCell.innerHTML = newData[i];
}
}
form.reset();
}
function deleteRow() {
var table = document.getElementById('table');
var input = document.getElementById('deleteRowInput');
}
//validating form
function validateForm() {
var f = document.getElementById('form');
if(f.fnaam.value == '') {
alert('Please fill in first name!');
return false;
}
if(f.lnaam.value == '') {
alert('Please fill in last name!');
return false;
}
if(f.points.value == '') {
alert('Please fill in points!');
return false;
}
if(isNaN(f.points.value)) {
alert('Points should be a number!')
return false
}
return true;
}
为简单起见,将data-
属性添加到包含相应行号的tr
元素。
addNumber
中的修改:
newRow.innerHTML = `<tr data-row-number="${rowNumber}"><td><i>${rowNumber}</i></td><tr>`;
deleteRow
函数可能看起来像这样:
function deleteRow() {
let table = document.getElementById('table');
let input = document.getElementById('deleteRowInput');
let n_rowToDelete = input.value;
document.querySelector ( 'tr[data-row-number="' + n_rowToDelete + '"]' ).remove();
}
注意:
...,请注意,在首次调用deleteRow
之后,既不会有连续的行号列表,也不会反映行在表行序列中的位置。