我有这个 html:
<table>
<tr>
<td>
Set right order
</td>
<td>
<span style = "display: block;">asd | <a href = '#' onclick = "moveChoiceTo(this, -1);">↑</a><a href = '#' onclick = "moveChoiceTo(this, 1);">↓</a></span>
<span style = "display: block;">dsa | <a href = '#' onclick = "moveChoiceTo(this, -1);">↑</a><a href = '#' onclick = "moveChoiceTo(this, 1);">↓</a></span>
<span style = "display: block;">qwe | <a href = '#' onclick = "moveChoiceTo(this, -1);">↑</a><a href = '#' onclick = "moveChoiceTo(this, 1);">↓</a></span>
<span style = "display: block;">ewq | <a href = '#' onclick = "moveChoiceTo(this, -1);">↑</a><a href = '#' onclick = "moveChoiceTo(this, 1);">↓</a></span>
</td>
</tr>
</table>
还有这个 JS:
function moveChoiceTo(elem_choice, direction)
{
var curr_index = -1; //index of elem that we should move
var td = elem_choice.parentElement.parentElement; //link to TD
for (var i = 0; i < td.children.length; i++) //determine index of elem that called this function
if (td.children[i].children[0] == elem_choice)
{
curr_index = i;
break;
}
if (curr_index == -1)
return;
if (curr_index == 0 && direction < 0) //if nowhere to move
return;
if (curr_index == td.children.length - 1 && direction > 0) //if nowhere to move
return;
var curr_child = td.children[curr_index]; //save current elem into temp var
td.children.splice(curr_index, 1); //here I getting exception that splice isn't supported by object, but arent this is array?
td.children.splice(curr_index + direction, 0, curr_child); //attempt to insert it
}
我收到不支持 splice
的异常,但这应该是一个数组并支持此方法?
我还必须通过哪些其他方式来更改 child 订单?
最佳答案
我将使用更简单(更好)的方法添加答案:
function moveChoiceTo(elem_choice, direction) {
var span = elem_choice.parentNode,
td = span.parentNode;
if (direction === -1 && span.previousElementSibling) {
td.insertBefore(span, span.previousElementSibling);
} else if (direction === 1 && span.nextElementSibling) {
td.insertBefore(span, span.nextElementSibling.nextElementSibling)
}
}
关键思想是使用 insertBefore方法得当。您也不需要从 DOM 中删除任何内容。
演示:http://jsfiddle.net/dq8a0ttt/
关于javascript - 如何更改 JS 中的子元素顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25850389/