总体思路是在table外部加个div,修改div的innerHtml实现改变tr顺序的效果
具体思路是
获取当前要移动tr行的rowIndex,在table中删除掉,然后循环table的rows,到了目标行再直接加进去,最后把整体的html赋值给div完成效果
js代码如下
//使行向上一行 function setRowUp(obj) { if (obj.parentNode.parentNode.rowIndex != 1) { var tab = obj.parentNode.parentNode.parentNode; var nowNodeInnerHtml = obj.parentNode.parentNode.innerHTML; var nowNowIndex = obj.parentNode.parentNode.rowIndex; tab.deleteRow(nowNowIndex); var newHtml = "<table cellpadding="5" cellspacing="0">"; newHtml += ("<TR style='font-weight: bold; text-align: center;'>" + tab.rows[0].innerHTML + "</TR>"); for (i = 1; i < tab.rows.length; i++) { if (i == (nowNowIndex - 1)) { newHtml += ("<TR>" + nowNodeInnerHtml + "</TR>"); } newHtml += ("<TR>" + tab.rows[i].innerHTML + "</TR>"); } newHtml += "</table>"; document.getElementById("divContent").innerHTML = newHtml; } } //使行向下一行 function setRowDown(obj) { if (obj.parentNode.parentNode.rowIndex != (document.getElementById("divContent").childNodes[0].rows.length - 1)) { var tab = obj.parentNode.parentNode.parentNode; var nowNodeInnerHtml = obj.parentNode.parentNode.innerHTML; var nowNowIndex = obj.parentNode.parentNode.rowIndex; tab.deleteRow(nowNowIndex); var newHtml = "<table cellpadding="5" cellspacing="0">"; newHtml += ("<TR style='font-weight: bold; text-align: center;'>" + tab.rows[0].innerHTML + "</TR>"); for (i = 1; i < tab.rows.length; i++) { if (i == (nowNowIndex + 1)) { newHtml += ("<TR>" + nowNodeInnerHtml + "</TR>"); } newHtml += ("<TR>" + tab.rows[i].innerHTML + "</TR>"); } //向下可能到表格现有行数外 额外处理 if (tab.rows.length == (nowNowIndex + 1)) { newHtml += ("<TR>" + nowNodeInnerHtml + "</TR>"); } newHtml += "</table>"; document.getElementById("divContent").innerHTML = newHtml; } }
测试html代码如下
<body> <div id="divContent"> <table cellpadding="5" cellspacing="0"> <tr style='font-weight: bold; text-align: center;'><td>工号</td><td>姓名</td></tr> <tr><td>0001 <input type="button" value="↑" onclick="setRowUp(this)" /> <input type="button" value="↓" onclick="setRowDown(this)" /> </td><td>姓名01</td></tr> <tr><td>0002 <input type="button" value="↑" onclick="setRowUp(this)" /> <input type="button" value="↓" onclick="setRowDown(this)" /> </td><td>姓名02</td></tr> <tr><td>0003 <input type="button" value="↑" onclick="setRowUp(this)" /> <input type="button" value="↓" onclick="setRowDown(this)" /> </td><td>姓名03</td></tr> <tr><td>0004 <input type="button" value="↑" onclick="setRowUp(this)" /> <input type="button" value="↓" onclick="setRowDown(this)" /> </td><td>姓名04</td></tr> <tr><td>0005 <input type="button" value="↑" onclick="setRowUp(this)" /> <input type="button" value="↓" onclick="setRowDown(this)" /> </td><td>姓名05</td></tr> </table> </div> </body>