jQuery移动任何给定的div

时间:2017-08-22 15:35:09

标签: jquery

如何使用jQuery执行此操作: 有4个带ID的div。单击div时,它会移动到另一个div(让我们称之为newDiv1),其他3移动到newDiv2。 我只能使用detachappendTo对1个特定div进行此操作,但我不知道如何将规则应用于所有这些。

HTML:

<div class="park1">
    <div id="car1">Car 1</div>
    <div id="car2">Car 2</div>
    <div id="car3">Car 3</div>
    <div id="car4">Car 4</div>
</div>
<div class="park2"></div>
<div class="park3"></div>
<div class="park4"></div>

JS:

// when click on car1, car1 will move to park2, the other 3 to park3
$("#car1").on("click", function() {
    $("#car1").detach().appendTo(".park2");

    $("#car2").detach().appendTo(".park3");
    $("#car3").detach().appendTo(".park3");
    $("#car4").detach().appendTo(".park3");
});

// when car 2 is already at park3, click on it, it moves to park4
$("#car2").on("click", function() {
    $("#car2").detach().appendTo(".park4");
});

当我点击4中的任何一个时,我需要这样做。

1 个答案:

答案 0 :(得分:1)

只需click移动元素。

并确保在div的{​​{1}}上应用正确的事件处理程序,具体取决于&#34; park&#34;它是......使用event delegation

&#13;
&#13;
// when click on car1, car1 will move to park2, the other 3 to park3
$(".park1").on("click", "div", function() {
  console.log("click on a car in park #1");
  
  // Move all other cars to park #3
  $(this).parent().children().not($(this)).appendTo(".park3");
  
  // Move the clicked car to park #2
  $(".park2").append($(this));
  
});

// when car 2 is already at park3, click on it, it moves to park4
$(".park3").on("click", "div", function() {
  console.log("click on a car in park #3");
  
  // Move the clicked car to park #4
  $(".park4").append($(this));
  
});
&#13;
.park1{
  border: 3px solid black;
  padding: 0.5em;
  margin: 1em;
}
.park2{
  border: 3px solid green;
  padding: 0.5em;
  margin: 1em;
}
.park3{
  border: 3px solid yellow;
  padding: 0.5em;
  margin: 1em;
}
.park4{
  border: 3px solid red;
  padding: 0.5em;
  margin: 1em;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="park1">
    <div id="car1">Car 1</div>
    <div id="car2">Car 2</div>
    <div id="car3">Car 3</div>
    <div id="car4">Car 4</div>
</div>
<div class="park2"></div>
<div class="park3"></div>
<div class="park4"></div>
&#13;
&#13;
&#13;