首页 > 解决方案 > 如何使用 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>'

标签: javascripthtml

解决方案


您可以分离孩子并

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>


推荐阅读