通过我自己的类克隆另一个元素的内容和顺序

时间:2016-05-18 10:19:37

标签: javascript jquery html

<ul id="item_one">
    <li class="one">List one</li>
    <li class="three">List three</li>
    <li class="five">List five</li>
    <li class="seven">List seven</li>
</ul>
<ul id="item_two">
    <li class="two">List two</li>
    <li class="four">List four</li>
    <li class="six">List six</li>
    <li class="eight">List eight</li>
</ul>

我有上面的HTML标记,我希望使用javascript / jQuery将上面的标记放入某个断点的下面标记中。

<ul id="item_one">
    <li class="one">List one</li>
    <li class="two">List two</li>
    <li class="three">List three</li>
    <li class="four">List four</li>
    <li class="five">List five</li>
    <li class="six">List six</li>
    <li class="seven">List seven</li>
    <li class="eight">List eight</li>
</ul>

我该怎么做?请帮帮我..

1 个答案:

答案 0 :(得分:0)

您可以在里面添加自定义数据attr,然后您可以使用unwrap()sort()

$('#item_two li').unwrap().appendTo('#item_one');

var ul = $('#item_one').find('li').sort((a, b) => {
  return $(a).data('id') - $(b).data('id')
})

$('#item_one').empty().append(ul);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="item_one">
  <li data-id="1" class="one">List one</li>
  <li data-id="3" class="three">List three</li>
  <li data-id="5" class="five">List five</li>
  <li data-id="7" class="seven">List seven</li>
</ul>
<ul id="item_two">
  <li data-id="2" class="two">List two</li>
  <li data-id="4" class="four">List four</li>
  <li data-id="6" class="six">List six</li>
  <li data-id="8" class="eight">List eight</li>
</ul>