2 回答
TA贡献1946条经验 获得超3个赞
您可以在表中找到当前行数,然后将其加 1 并将其添加到新行。
您可以通过以下方式找到表中的行数
const table = document.getElementById("myTable");
const numOfRows = table.getElementsByTagName('tr');
console.log(numOfRows.length);
更新addRow()的方法将是
function addRow() {
//Get data from filled in 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) {
//Put data in table
var table = document.getElementById('table');
const rows = table.getElementsByTagName('tr');
const currentRow = rows.length + 1;
var newRow = table.insertRow();
const firstCell = newRow.insertCell(0);
firstCell.innerHTML = currentRow;
for(var i = 1; i <= 3; i++) {
var newCell = newRow.insertCell(i);
newCell.innerHTML = newData[i];
}
}
form.reset();
}
jsfiddle 演示https://jsfiddle.net/m9rh1uvw/
TA贡献1815条经验 获得超13个赞
此代码可能会解决您的问题。
var btn = document.getElementById('btn');
btn.onclick = myFunction;
function myFunction() {
validateForm()
addRow()
}
var rowNumber = 0;
function addRow() {
//Get data from filled in 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();
newRow.innerHTML = `<tr><td>${rowNumber}</td></tr>`;
for(var i = 0; i < 3; i++) {
newRow.innerHTML += `<tr><td>${newData[i]}</td></tr>`;
}
}
form.reset();
}
function validateForm() {
var f = document.getElementById('form');
if(f.fname.value == '') {
alert('Please fill in first name');
return false;
}
if(f.lname.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;
}
input[type="text"] {
padding:10px;
font-size:16px;
}
#btn {
padding:15px 25px;
border: 0;
background: #f90;
color: #fff;
border-radius: 3px;
font-size:16px;
cursor: pointer;
margin: 20px auto;
}
#table tr td {
font-size: 16px;
padding: 10px 20px;
border: 2px solid #000;
font-family: sans-serif;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form action="" id="form">
<input type="text" name="fname" placeholder="Fname">
<input type="text" name="lname" placeholder="Lname">
<input type="text" name="points" placeholder="Points">
</form>
<button id="btn">Add Row</button>
<table id="table"></table>
</body>
</html>
添加回答
举报