gpt4 book ai didi

javascript - 行添加到 thead 而不是 tbody

转载 作者:行者123 更新时间:2023-12-01 03:35:24 25 4
gpt4 key购买 nike

以下 HTML 文件包含一个添加按钮。单击时,它应该添加一行。当我检查代码时,我发现添加在 thead 下的行而不是 tbody 标记。这是为什么?如何避免这种情况?

addButton = document.getElementById("add-button");
table = document.getElementById("data-table");

addButton.addEventListener('click', add, false);

function add() {

var tableLength = table.length;
var row = table.insertRow(tableLength);

var col1 = row.insertCell(0);
var col2 = row.insertCell(1);

col1.innerHTML = "col1";
col2.innerHTML = "col2";
}

var delLink = document.getElementById("delete-link");
delLink.addEventListener('click', del, false);

function del() {
var rowstoDelete = table.querySelectorAll("tbody tr");
[].slice.call(rowstoDelete).forEach(function(row) {
row.remove()
});

}
<table align="center" cellspacing=1 cellpadding=1 id="data-table" border=1 class="data-table">
<thead>

<tr id="head" class="head">
<th class="head">Name</th>
<th class="head">Action</th>
</tr>

<tr id="initial-row" class="initial-row">
<th><input type="text" id="text-field"></th>
<th><input type="button" class="add-button" id="add-button" value="Add"></th>
</tr>

</thead>

<tbody>

</tbody>

</table>

<a id="delete-link" href="#"> Delete all rows Except the first two</a>

最佳答案

在这里检查我的 fiddle enter link description here

你没有做的是专门为tbody看。在这里回答How to insert row in HTML table body in javascript?

    addButton=document.getElementById("add-button");
table=document.getElementById("data-table");

addButton.addEventListener('click',add,false);

function add()
{

var tableLength=table.length;
var row = table.getElementsByTagName('tbody')[0].insertRow(tableLength);

var col1 = row.insertCell(0);
var col2 = row.insertCell(1);

col1.innerHTML="col1";
col2.innerHTML="col2";
}

var delLink = document.getElementById("delete-link");
delLink.addEventListener('click',del,false);

function del()
{
var rowstoDelete = table.querySelectorAll("tbody tr");
[].slice.call(rowstoDelete).forEach(function(row) {
row.remove()
});

}

关于javascript - 行添加到 thead 而不是 tbody,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44304817/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com