私がしたいのは、2 つの HTML DOM ノードを交換することです。
次の HTML リストと下のスワップ ボタンを見てみましょう。
<ul class="center-text">
<li>0</li>
<li>1</li>
<li>2</li>
</ul>
<form class="center-text">
<button id="swapButton">Swap</button>
</form>
そして、ここに私のJSコードがあります:
// the "ready" method is the only jQuery method used in the code
$(document).ready(function(){
document.getElementById("swapButton").onclick = function() {
var ul = document.getElementsByTagName("ul")[0];
// pseudo-swapping: insert "child2" before "child0"
// (indexes are 1 and 5 because of the TextNodes between list nodes)
ul.insertBefore(ul.childNodes.item(5), ul.childNodes.item(1));
}
});
スワップ ボタンをクリックすると、次のようになります
。アイテムが実際にスワップされます。しかし、どういうわけか (1/4 秒としましょう) 秒後に元の位置に戻ります。つまり、自動的に元に戻ります。私の質問は:なぜですか?
PS: コードは単に教育目的のためのものであり、ドアの後ろで何が起こっているのかを理解しようとするだけなので、代替の jQuery メソッドを投稿しないでください。