首页 > 解决方案 > jQuery - 使用 click 函数内部的每个移动 div

问题描述

我想将.movediv放置在单击.destination时的内部,否则单击if的.gridview内部。.item.listview

当前,当单击任一视图时,.movediv 会被迭代多次。如何更改代码以便.move每个 div 附加一次.item

$(".gridview").on("click", function() {
  $(".item").each(function() {
    var $this = $(this);
    $this.find(".move").appendTo(".destination");
  });
  var $this = $(this).closest(".container");
  $this.find(".listview").removeClass("active");
  $this.find(".gridview").addClass("active");
  $this.find(".block").css("display", "flex");
});

$(".listview").on("click", function() {
  $(".item").each(function() {
    var $this = $(this);
    var $list = $this.closest(".list");
    $this.find(".move").appendTo(".item");
  });
  var $this = $(this).closest(".container");
  $this.find(".gridview").removeClass("active");
  $this.find(".listview").addClass("active");
});
.item {
  margin: 1.3rem 0;
  border: 2px solid;
}

.destination {
  height: 35px;
  border: 3px solid
}

.move {
  height: 25px;
  border: 2px solid;
  background: green
}

.block {
  display: none;
  height: 45px;
  width: 45px;
  border: 2px solid green;
}

.active {
  background: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="gridview">Grid</div>
  <div class="listview active">List</div>
  <div class="list">
    <div class="item">
      <div class="destination"></div>
      <div class="block"></div>
      <div class="move"></div>
    </div>
    <div class="item">
      <div class="destination"></div>
      <div class="block"></div>
      <div class="move"></div>
    </div>
  </div>
</div>

标签: jquery

解决方案


你可以试试下面的代码吗?

$(".gridview").on("click", function() {
  $.each($(".list .item"),function(i,v){ 
   $(this).find(".destination").append($(v).find(".move"))
 })
  var $this = $(this).closest(".container");
  $this.find(".listview").removeClass("active");
  $this.find(".gridview").addClass("active");
  $this.find(".block").css("display", "flex");
});

$(".listview").on("click", function() {
   $.each($(".list .item"),function(i,v){
      $(this).append($(v).find(".destination .move"))
    })
  var $this = $(this).closest(".container");
  $this.find(".gridview").removeClass("active");
  $this.find(".listview").addClass("active");
});

推荐阅读