如何防止jQuery apendTo复制内容

时间:2019-10-28 01:06:09

标签: javascript jquery

我正在尝试通过使用jQuery prependTo函数在另一个div(.imageContainer a)中移动div(.titleContainer),但是由于某些原因,先前附加的内容也被添加到了接收附加内容的元素中元件。谢谢!

$(document).ready(function () {
    $('.titleContainer').each(function(){
        $(this).prependTo('.imageContainer a');
    });
});
.imageContainer{
    background: rgb(144, 144, 221);
}
.card{
    margin-right: 20px; 
    flex: 0 0 30%;
}
h3{
    color: black
}
body{
    display: flex;
    justify-content: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
    <div class="card">
        <div class="titleContainer">
            <h3>title1</h3>
        </div>
        <div class="imageContainer">
            <a href="">
                <img src="" alt="">
            </a>
        </div>
    </div>

    <div class="card">
        <div class="titleContainer">
            <h3>title2</h3>
        </div>
        <div class="imageContainer">
            <a href="">
                <img src="" alt="">
            </a>
        </div>
    </div>

    <div class="card">
        <div class="titleContainer">
            <h3>title3</h3>
        </div>
        <div class="imageContainer">
            <a href="">
                <img src="" alt="">
            </a>
        </div>
    </div>

</body>

2 个答案:

答案 0 :(得分:2)

您需要在同一.imageContainer中定位.card。使用'.imageContainer a'将定位到所有a

$(document).ready(function() {
  $('.titleContainer').each(function() {
    $(this).prependTo($(this).closest('.card').find('.imageContainer a'));
  });
});
.imageContainer {
  background: rgb(144, 144, 221);
}

.card {
  margin-right: 20px;
  flex: 0 0 30%;
}

h3 {
  color: black
}

body {
  display: flex;
  justify-content: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body>
  <div class="card">
    <div class="titleContainer">
      <h3>title1</h3>
    </div>
    <div class="imageContainer">
      <a href="">
        <img src="" alt="">
      </a>
    </div>
  </div>

  <div class="card">
    <div class="titleContainer">
      <h3>title2</h3>
    </div>
    <div class="imageContainer">
      <a href="">
        <img src="" alt="">
      </a>
    </div>
  </div>

  <div class="card">
    <div class="titleContainer">
      <h3>title3</h3>
    </div>
    <div class="imageContainer">
      <a href="">
        <img src="" alt="">
      </a>
    </div>
  </div>

</body>

答案 1 :(得分:-1)

$(function(){
    $('.titleContainer').each(function(){
      $(this).prependTo($(this).next().find('a'));
    });
});

Codepen

注意:$(function(){}) === $(document).ready(function(){});