javascript - 如何使用 Javascript 编辑表格行的 rowIndex
问题描述
这可能是非常规的,但我想知道如何编辑表格行的索引?
所以我可以像这样获取表行的当前 rowIndex
var rowIndex = document.getElementsByClassName('edit-engagement-row')[0].rowIndex
但是,如果我想像这样更改 rowIndex
var rowIndex = document.getElementsByClassName('edit-engagement-row')[0].rowIndex
rowIndex = index
我收到以下警报
Uncaught TypeError: Cannot assign to read only property 'rowIndex' of object '#<HTMLTableRowElement>'
解决方案
您可以分离孩子并
function detach(element) {
return element.parentElement.removeChild(element);
}
function move(src, dest, isBefore) {
dest.insertAdjacentElement(isBefore ? 'beforebegin' : 'afterend', detach(src));
}
function children(element, selector) {
return element.querySelectorAll(selector);
}
function child(element, selector, index) {
return children(element, selector)[index];
}
function row(table, index) {
// Generic Version: return child(table.querySelector('tbody'), 'tr', index);
return table.querySelector('tbody').querySelector(`tr:nth-child(${index + 1})`);
}
function moveRow(table, fromIndex, toIndex, isBefore) {
move(row(table, fromIndex), row(table, toIndex), isBefore);
}
// Move "Eve" (index = 2) to be before "Jack" (index = 0)
moveRow(document.querySelector('table'), 2, 0, true);
table {
border-collapse: collapse;
width: 50vw;
margin: 0 auto;
}
table, th, td {
border: thin solid grey;
}
th, td {
text-align: center;
}
<table>
<thead>
<tr><th>Firstname</th><th>Lastname</th><th>Age</th></tr>
</thead>
<tbody>
<tr><td>Jack</td><td>Brown</td><td>42</td></tr>
<tr><td>Jill</td><td>Smith</td><td>50</td></tr>
<tr><td>Eve</td><td>Jackson</td><td>94</td></tr>
</tbody>
</table>
推荐阅读
- c++ - 指向具有指针成员的对象的指针数组的析构函数
- python - 模型并行不适用于增加 tensorflow1.12 中的模型大小?
- spring-boot - 运行 Azure DevOps Pipeline 时如何跳过构建测试(Spring Boot Maven 项目)
- python - 如何使用标签将 txt 文件数据集分类为两个数据集?
- networking - 为数据包处理添加延迟 (omnet++)
- google-sso - 带有 Itop 的 Google Workspace SSO
- firebase - 有没有办法仅将 BigQuery 镜像 Firebase Firestore 用于 CREATE 和 DELETE?
- performance - SOLID 原则可以用于高性能代码吗?
- jpa - JPA 多对多映射
- python - 在脚本目录之外时在终端中执行 Python 脚本