gpt4 book ai didi

javascript - 使用javascript交换行

转载 作者:太空宇宙 更新时间:2023-11-04 14:45:23 24 4
gpt4 key购买 nike

我有多个由 for 条件生成的行,上下有 2 个图标。单击向上,所选行应向上移动一级,单击向下,所选行应向下移动一级

<html>
<head>
<body>
<form name="myForm">

<table id="mainTable" border="1" width="100%">

<script>
document.write('<tr>')
document.write('<td>')
document.write('row1')
document.write('</td>')
document.write('</tr>')

document.write('<tr>')
document.write('<td>')
document.write('row2')
document.write('</td>')
document.write('</tr>')
document.write('</table>')

document.write('<table>')
document.write('<tr>')
document.write('<td>')
document.write('<input type="button" value=" move UP " onClick="swapRowUp(getRowIndex(this))"</input>')>
document.write('<input type="button" value="move DOWN" onClick="swapRowDown(getRowIndex(this))"</input>')>
document.write('</td>')
document.write('</tr>')
document.write('</table>')
</script>
</table>

</form>
</body>
</head>
</html>
<script>
var mainTable = document.getElementById("mainTable");
function getRowIndex(el)
{
while( (el = el.parentNode) && el.nodeName.toLowerCase() !== 'tr' );

if( el )
alert(el.rowIndex);
return el.rowIndex;
}

function swapRowUp(chosenRow) {
if (chosenRow.rowIndex != 0) {
moveRow(chosenRow, chosenRow.rowIndex-1);
}
}
function swapRowDown(chosenRow) {
if (chosenRow.rowIndex != mainTable.rows.length-1) {
moveRow(chosenRow, chosenRow.rowIndex+1);
}
}

function moveRow(targetRow, newIndex) {
if (newIndex > targetRow.rowIndex) {
newIndex++;
}

var mainTable = document.getElementById('mainTable');

var theCopiedRow = mainTable.insertRow(newIndex);


for (var i=0; i<targetRow.cells.length; i++) {
var oldCell = targetRow.cells[i];
var newCell = document.createElement("TD");
newCell.innerHTML = oldCell.innerHTML;
theCopiedRow.appendChild(newCell);
copyChildNodeValues(targetRow.cells[i], newCell);
}
//delete the old row
mainTable.deleteRow(targetRow.rowIndex);
}


function copyChildNodeValues(sourceNode, targetNode) {
for (var i=0; i < sourceNode.childNodes.length; i++) {
try{
targetNode.childNodes[i].value = sourceNode.childNodes[i].value;
}
catch(e){

}
}
}

</script>

我无法执行交换操作,我得到的 cellIndex 为 null

最佳答案

你可以使用一些合理的 JavaScript

up.addEventListener("click", function moveRowUp() {
var row = this.parentNode.parentNode,
sibling = row.previousElementSibling,
parent = row.parentNode;

parent.insertBefore(row, sibling);
});

一些合理的 HTML

<table>
<tbody>
<tr>
<td> 1 </td>
<td> filler </td>
</tr>
<tr>
<td> 2 </td>
<td> <button id="up">up</button> </td>
</tr>
</tbody>
</table>

Live Example

关于javascript - 使用javascript交换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8862006/

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