如何在JS中更改子元素顺序?

时间:2014-09-15 14:27:52

标签: javascript html

我有这个HTML:

<table>
    <tr>
        <td>
            Set right order
        </td>
        <td>
            <span style = "display: block;">asd | <a href = '#' onclick = "moveChoiceTo(this, -1);">&uarr;</a><a href = '#' onclick = "moveChoiceTo(this, 1);">&darr;</a></span>
            <span style = "display: block;">dsa | <a href = '#' onclick = "moveChoiceTo(this, -1);">&uarr;</a><a href = '#' onclick = "moveChoiceTo(this, 1);">&darr;</a></span>
            <span style = "display: block;">qwe | <a href = '#' onclick = "moveChoiceTo(this, -1);">&uarr;</a><a href = '#' onclick = "moveChoiceTo(this, 1);">&darr;</a></span>
            <span style = "display: block;">ewq | <a href = '#' onclick = "moveChoiceTo(this, -1);">&uarr;</a><a href = '#' onclick = "moveChoiceTo(this, 1);">&darr;</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不支持的异常,但这应该是一个数组并支持这种方法? 还有什么方法可以改变孩子的秩序?

2 个答案:

答案 0 :(得分:4)

HTMLCollection不支持Splice,你需要使用.removeChild和.insertBefore之类的东西:

var before = td.children[curr_index + direction];
var child = td.children[curr_index];

td.removeChild(child);
td.insertBefore(child, before); //attempt to insert it      

答案 1 :(得分:4)

我将用更简单(更好)的方法添加答案:

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/