总体思路是在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 = "
"; newHtml += (" " + tab.rows[0].innerHTML + "
"); for (i = 1; i < tab.rows.length; i++) { if (i == (nowNowIndex - 1)) { newHtml += (" " + nowNodeInnerHtml + "
"); } newHtml += (" " + tab.rows[i].innerHTML + "
"); } newHtml += "
"; 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 = "
"; newHtml += (" " + tab.rows[0].innerHTML + "
"); for (i = 1; i < tab.rows.length; i++) { if (i == (nowNowIndex + 1)) { newHtml += (" " + nowNodeInnerHtml + "
"); } newHtml += (" " + tab.rows[i].innerHTML + "
"); } //向下可能到表格现有行数外 额外处理 if (tab.rows.length == (nowNowIndex + 1)) { newHtml += (" " + nowNodeInnerHtml + "
"); } newHtml += "
"; document.getElementById("divContent").innerHTML = newHtml; } }
测试html代码如下