javascript - 在 html 表的 top-1 位置添加一行
问题描述
function addRowtoTop(first) {
// get input values
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var city = document.getElementById('city').value;
var country = document.getElementById('country').value;
// get the html table
// 0 = the first table
var table = document.getElementsByTagName('table')[0];
// add new empty row to the table
// 0 = in the top
// table.rows.length = the end
// table.rows.length/2+1 = the center
var newRow = table.insertRow((table.rows.length / 0));'
我一直试图在 html 表的 top-1 位置添加一行,但不知道如何。通过这一行,var newRow = table.insertRow((table.rows.length / 0));
我可以在顶部添加行,但它被添加到标题部分上方。提前致谢
解决方案
您需要将头部存储在一个变量中,然后是新行,然后取其余行,最后只需 table.innerHTML = newTable;
function addRow(){
var table = document.querySelector('table');
var Head = table.children[0].children[0].outerHTML;
var newRow = '<tr><td>newShoes</td><td>Shoes</td><td>Shoes</td></tr>';
var restOfTheTable = '';
for(var i = 1; i<=table.children[0].children.length-1; i++){
restOfTheTable += (table.children[0].children[i].outerHTML);
}
table.innerHTML = `${Head}${newRow}${restOfTheTable}`;
}
<table>
<tr>
<td>name</td>
<td>Price</td>
<td>Location</td>
</tr>
<tr>
<td>Shoes</td>
<td>Shoes</td>
<td>Shoes</td>
</tr>
<tr>
<td>Shoes</td>
<td>Shoes</td>
<td>Shoes</td>
</tr>
</table>
<button onclick="addRow()">add row</button>
推荐阅读
- angular - 当父级更改值时,Angular 7不会更新子级
- c# - 使用反射分割对象
- cloudflare - Cloudflare 动态 dns
- android - 在 MQTT 服务器上发布共享意图
- java - 将 RDF .ttl 文件合并到一个文件数据库中 - 过滤并仅保留所需的数据/三元组
- powershell - 按日期创建文件夹,然后重命名具有先前日期前缀的文件,然后按扩展名将文件移动到文件夹中
- security - SAP 安全审计日志 (SAL) 是否加密?
- cypress - 未捕获的 AssertionError:未设置环境,中止运行柏树问题
- r - 带引号的字符串中的 EOF 以使用 read.table 导入所有带有 lapply tsv 数据的 tsv 文档
- javascript - 获取 xmlHttpRequest 请求大小