【发布时间】:2023-03-31 14:47:01
【问题描述】:
我正在做一个项目,我有一个 HTML 表格,我需要为用户提供交换两个 HTML 表格单元格内容的选项。
具体来说,用户可以单击以选择一行,然后选择向上或向下移动该行。实际上,他们只是在移动代表信息的第 2 列的内容。第 1 列代表顺序,它不会改变。
该表总共有两列。 第 1 列将代表线性顺序(即 1-10),它不会改变。 第 2 列将是数据库提供的信息(在我提供姓氏的示例代码中)。
我构建了两个按钮,向上和向下,并使用了两个 Javascript 函数,允许用户选择一行并将其向上或向下移动。
当前代码成功移动一整行上下移动,但是我只需要第2列的单元格内容上下移动。
请查看提供的代码和 JSFiddle 并告诉我如何解决这个问题?提前致谢!
var index; // variable to set the selected row index
function getSelectedRow() {
var table = document.getElementById("table");
for (var i = 1; i < table.rows.length; i++) {
table.rows[i].onclick = function() {
// clear the selected from the previous selected row
// the first time index is undefined
if (typeof index !== "undefined") {
table.rows[index].classList.toggle("selected");
}
index = this.rowIndex;
this.classList.toggle("selected");
};
}
}
getSelectedRow();
function upNdown(direction) {
var rows = document.getElementById("table").rows,
parent = rows[index].parentNode;
if (direction === "up") {
if (index > 1) {
parent.insertBefore(rows[index], rows[index - 1]);
// when the rowgo up the index will be equal to index - 1
index--;
}
}
if (direction === "down") {
if (index < rows.length - 1) {
parent.insertBefore(rows[index + 1], rows[index]);
// when the row go down the index will be equal to index + 1
index++;
}
}
}
tr {
cursor: pointer
}
.selected {
background-color: red;
color: #fff;
font-weight: bold
}
button {
margin-top: 10px;
background-color: #eee;
border: 2px solid #00F;
color: #17bb1c;
font-weight: bold;
font-size: 25px;
cursor: pointer
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta content="width=device-width, initial-scale=1, shrink-to-fit=no" name="viewport">
<meta content="30" http-equiv="refresh">
<title> {{.Title}} </title>
<style>
.bd-placeholder-img {
font-size: 1.125rem;
text-anchor: middle;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
}
@media (min-width: 768px) {
.bd-placeholder-img-lg {
font-size: 3.5rem;
}
}
</style>
</head>
<body>
<header>
</header>
<main>
<table id="table" border="1">
<tr>
<th>Order</th>
<th>Last Name</th>
</tr>
<tr>
<td>1</td>
<td>Smith</td>
</tr>
<tr>
<td>2</td>
<td>Johnson</td>
</tr>
<tr>
<td>3</td>
<td>Roberts</td>
</tr>
<tr>
<td>4</td>
<td>Davis</td>
</tr>
<tr>
<td>5</td>
<td>Doe</td>
</tr>
</table>
<button onclick="upNdown('up');">↑</button>
<button onclick="upNdown('down');">↓</button>
</main>
<!-- Bootstrap core JavaScript -->
<script src="/vendor/jquery/jquery.min.js"></script>
<script src="/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="/js/sidebar.js"></script>
</body>
</html>
【问题讨论】:
-
所以你的意思是像这样工作,考虑到第 4 行和第 5 行有 2 个项目。您只需要交换第二列值。 (第一列是线性顺序,比如行号等),对吧?
-
我没有看过你的代码,但这个问题让我想知道,你能不能把 contents 复制到一个新的单元格,而不是尝试“移动一个单元格” ?
-
@AbinThaha 是的,第 1 列本质上将按行号顺序排列。我只需要更改第 2 列的内容。感谢您的快速回复。
-
@wazz 是的,我愿意复制内容,并且我研究过 InnerHTML,但我无法使用它来抓取第 2 列。注意:我不知道我有多少行。因此,例如,我不能简单地交换 id=td1 和 id=td2 的内容。
标签: javascript html css dom html-table