如何将span作为li中的最后一个对象追加?

时间:2017-08-11 19:06:21

标签: javascript append insertafter

我目前有这行代码



<div id="news-articles">
  <ul class="display-posts-listing">
    <li class="listing-item">
      <span></span>
      <span class="category-display"></span>
      <span></span>
      <span></span>
    </li>
  </ul>
</div>
&#13;
&#13;
&#13;

我需要它看起来像这样(*注意 - 有多个uls。因此它必须是每个&#34; span.category-display&#34;它们最后会在他们自己的父li中添加):

&#13;
&#13;
//Ive been trying to use this js script, but so far no results. Can anyone assist? Thanks so much! :





  $("#news-articles .category-display").each(function() {
                $(this).prev("li.listing-item").append(this);
        });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="news-articles">
  <ul class="display-posts-listing">
    <li class="listing-item">
      <span></span>
      <span></span>
      <span></span>
      <span class="category-display"></span>
    </li>
  </ul>
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

$.prev()选择上一个兄弟姐妹。您想使用$.parent()

我会这样写:

$(".listing-item").each(function(){
    $this = $(this);
    var $elem = $this.find(".category-display").detach();
    $elem.appendTo($this);
});

答案 1 :(得分:0)

只需将跨度附加到LI,它将最终位于底部

$('.listing-item').append(function() {
  return $(this).find('.category-display');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="news-articles">
  <ul class="display-posts-listing">
    <li class="listing-item">
      <span>1</span>
      <span class="category-display">4</span>
      <span>2</span>
      <span>3</span>
    </li>
  </ul>
  <br />
  <ul class="display-posts-listing">
    <li class="listing-item">
      <span>1</span>
      <span class="category-display">4</span>
      <span>2</span>
      <span>3</span>
    </li>
  </ul>
</div>