将一个 div 替换为另一个 - jquery

Replace one div with another - jquery

我有 4 个 div,每个都有上下箭头。 如果用户单击顶部箭头 - 当前 div 将位置更改为更高的 div,反之亦然。

我该怎么做? 此代码适用于 "bottom arrow" 并且不起作用...

$("button.down").click(function(){

var aDiv = $(this).parent();
var dDiv = $(this).parent().next("div");

$(this).parent().next("div").replaceWith(aDiv);
$(this).parent().replaceWith(dDiv);

});

http://jsfiddle.net/gjkhf81u/

您可能正在寻找 insertBefore:

var div = $(theCurrentDiv);
var prev = div.prev();
if (prev[0]) {
    div.insertBefore(div.prev());
}

该代码将当前 div 移动到其同级(如果有)的前面。还有相关的 before,它是相反的。

insertBefore 示例:

$("input[type=button]").click(function() {
  var div = $(".current");
  var prev = div.prev();
  if (prev[0]) {
    div.insertBefore(prev);
  }
});
.current {
  color: green;
  font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="button" value="Up">
<div>
  <div>one</div>
  <div>two</div>
  <div>three</div>
  <div class="current">four</div>
</div>

或者,您可以交换 div 的内容?

<div class="x"> Hello World </div>
<div class="y"> Bye World </div>

    $("button.down").click(function() {
        var temp = $(".x").html();
        $(".x").html() = $(".y").html();
        $(".y").html() = temp;
    });

mentioned, you want to use insertBefore and insertAfter

当您在 DOM 中的不同位置插入节点时,它会被移动。

$("button.down").click(function(){
  var aDiv = $(this).parents(".container");
  var nextDiv = aDiv.next(".container");
  aDiv.insertAfter(nextDiv);
});

$("button.up").click(function(){
  var aDiv = $(this).parents(".container");
  var prevDiv = aDiv.prev(".container");
  aDiv.insertBefore(prevDiv);
});
.container {
    width: 100%;
    height: 25px; 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="background-color: green;" class="container">
<button class="up">Up</button>
<button class="down">Down</button>
</div>

<div style="background-color: red;" class="container">
<button class="up">Up</button>
<button class="down">Down</button>
</div>

<div style="background-color: yellow;" class="container">
<button class="up">Up</button>
<button class="down">Down</button>
</div>

<div style="background-color: blue;" class="container">
<button class="up">Up</button>
<button class="down">Down</button>
</div>