使用纯javascript交换2 div的索引

时间:2014-03-27 19:25:44

标签: javascript

我有一个父div,它有9个div正在尝试交换两个div的索引。以下是我的代码:

HTML:

<div id="cont" class="container">
    <div class="no">1</div>
    <div class="no">2</div>
    <div class="no">3</div>
    <div class="blank"></div>
    <div class="no">4</div>
    <div class="no">5</div>
    <div class="no">6</div>
    <div class="no">7</div>
    <div class="no">8</div>
</div>

现在我想交换第5和第6个索引元素。我不知道如何在JavaScript中做到这一点。我知道有一个名为.index()的函数,但是如何在纯JS中执行此操作。

1 个答案:

答案 0 :(得分:0)

以下是一项实施:http://jsfiddle.net/x8hWj/2/

function swap(idx1, idx2) {
    var container = document.getElementById('cont');
    // ditch text nodes and the like
    var children = Array.prototype.filter.call(
        container.childNodes,
        function(node) {
            return node.nodeType === 1;
        }
    );
    // get references to the relevant children
    var el1 = children[idx1];
    var el2 = children[idx2];
    var el2next = children[idx2 + 1];

    // put the second element before the first
    container.insertBefore(el2, el1);
    // now put the first element where the second used to be
    if (el2next) container.insertBefore(el1, el2next);
    else container.appendChild(el1);
}

首先获取所有元素子节点的列表,然后使用insertBefore重新排列它们。

相关问题