我创建了一个表。我需要使用javascript添加一个新行。任何人都可以解决它。
<head>
<script>
var num=1;
function addrow(){
num++;
var x = document.getElementById("add");
x.innerHTML= x.innerHTML +"<tr><td>Content_"+num+"</td></tr>";
}
</script>
<title>Add new row with js</title>
</head>
<body>
<table>
<tr><td>Content_1</td></tr>
//* I wanted to add a new row here *//
<tr><td>Content_End</td><td><button onclick="addrow()">+</button></td></tr>
</table>
</body>
我想在行之间添加一个新行!!有人可以帮忙吗? 提前谢谢!
答案 0 :(得分:1)
这样做
<head>
<script>
var num=1;
function addrow(){
var table = document.getElementById("add");
var row = table.insertRow(num);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "NEW CELL"+num;
cell2.innerHTML = "NEW CELL"+num;
num++;
}
</script>
<title>Add new row with js</title>
</head>
<body>
<table id="add">
<tr><td colspan="2">Content_1</td></tr>
<tr><td>Content_End</td><td><button onclick="addrow()">+</button></td></tr>
</table>
</body>
小提琴:Demo
答案 1 :(得分:1)
var num=1;
function addrow(){
var table = document.getElementById("add");
var row = table.insertRow(num);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "NEW CELL"+num;
cell2.innerHTML = "NEW CELL"+num;
num++;
}
这样可行:)
答案 2 :(得分:0)
您忘记将id
添加到您的表格中。此外,每行不能有td
个不同的数量。如果您希望一个单元格占用两列的空格,则添加colspan="2"
<head>
<script>
var num=1;
function addrow(){
num++;
var x = document.getElementById("add");
x.innerHTML= x.innerHTML +"<tr><td>Content_"+num+"</td></tr>";
}
</script>
<title>Add new row with js</title>
</head>
<body>
<table id="add">
<tr><td colspan="2">Content_1</td></tr>
<tr><td>Content_End</td><td><button onclick="addrow()">+</button></td></tr>
</table>
</body>