javascript - 如何更改 JS 中的子元素顺序?

标签 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 的异常,但这应该是一个数组并支持此方法? 我还必须通过哪些其他方式来更改 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/

相关文章:

html - css ul li 100% 使用固定 div 内的空间但动态 li

javascript - 如果任一 div 可见,jQuery 将隐藏

javascript - 在两个解耦的 javascript 模块之间传输数据的 PubSub 模式替代方案

javascript - Angular Mat AutoComplete 不显示/显示从后端返回的对象的下拉列表

javascript - 使用 ".click()"仍会触发禁用按钮

javascript - 如果渲染器进程关闭, Electron 全局变量垃圾会被收集吗?

html - 网站元素在 IE 中不起作用

javascript - react-native-scrollable-tab-view 上的无形边距

javascript - 使用 AJAX 上传 XML 文件

javascript - 将 div 高度设置为等宽 ( javascript )