总体思路是在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>" + 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>" + 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> <table cellpadding="5" cellspacing="0"> <tr><td>工号</td><td>姓名</td></tr> <tr><td>0001 <input type="button" value="↑" /> <input type="button" value="↓" /> </td><td>姓名01</td></tr> <tr><td>0002 <input type="button" value="↑" /> <input type="button" value="↓" /> </td><td>姓名02</td></tr> <tr><td>0003 <input type="button" value="↑" /> <input type="button" value="↓" /> </td><td>姓名03</td></tr> <tr><td>0004 <input type="button" value="↑" /> <input type="button" value="↓" /> </td><td>姓名04</td></tr> <tr><td>0005 <input type="button" value="↑" /> <input type="button" value="↓" /> </td><td>姓名05</td></tr> </table> </div> </body>
总结
以上所述是小编给大家介绍的js操作table中tr的顺序实现上移下移一行的效果,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!
您可能感兴趣的文章: