jQuery:appendTo在每个匹配项中只有一次

问题描述 投票:0回答:1

需要将span .cat的内容扔到上面的div,但是此事件将所有span .cat扔到每个div

在出门的路上

date category category2 category3
date category category2 category3
date category category2 category3

我需要

date category
date category2
date category3

$(document).ready(function() {
  $('.bdt-post-grid-category').wrapInner('<span class="bdt-post-grid-date cat"></span>');
  $('.bdt-post-grid-date.cat').appendTo($(".bdt-post-grid-meta"));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="bdt-post-grid-meta bdt-subnav bdt-flex-middle">
  <span class="bdt-post-grid-date">date</span>
</div>
<div class="bdt-post-grid-category bdt-position-small bdt-position-top-left">
  <a href="#" rel="category tag">category</a>
</div>

<div class="bdt-post-grid-meta bdt-subnav bdt-flex-middle">
  <span class="bdt-post-grid-date">date</span>
</div>
<div class="bdt-post-grid-category bdt-position-small bdt-position-top-left">
  <a href="#" rel="category tag">category2</a>
</div>

<div class="bdt-post-grid-meta bdt-subnav bdt-flex-middle">
  <span class="bdt-post-grid-date">date</span>
</div>
<div class="bdt-post-grid-category bdt-position-small bdt-position-top-left">
  <a href="#" rel="category tag">category3</a>
</div>
javascript jquery html append
1个回答
0
投票

使用.each()分别处理它们,只是追加到上一个元素。

$(document).ready(function() {
  $('.bdt-post-grid-category').wrapInner('<span class="bdt-post-grid-date cat"></span>');
  $('.bdt-post-grid-date.cat').each(function() {
    $(this).appendTo($(this).closest(".bdt-post-grid-category").prev());
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="bdt-post-grid-meta bdt-subnav bdt-flex-middle">
  <span class="bdt-post-grid-date">date</span>
</div>
<div class="bdt-post-grid-category bdt-position-small bdt-position-top-left">
  <a href="#" rel="category tag">category</a>
</div>

<div class="bdt-post-grid-meta bdt-subnav bdt-flex-middle">
  <span class="bdt-post-grid-date">date</span>
</div>
<div class="bdt-post-grid-category bdt-position-small bdt-position-top-left">
  <a href="#" rel="category tag">category2</a>
</div>

<div class="bdt-post-grid-meta bdt-subnav bdt-flex-middle">
  <span class="bdt-post-grid-date">date</span>
</div>
<div class="bdt-post-grid-category bdt-position-small bdt-position-top-left">
  <a href="#" rel="category tag">category3</a>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.