简体   繁体   English

使用Javascript / jQuery排序无序列表

[英]Sort unordered list with Javascript / jQuery

I am creating unordered lists dynamically. 我正在动态创建无序列表。 This creates an output similar to this: 这将创建类似于以下的输出:

<ul>
    <li>item 1</li>
    <li>item 2</li>
    <li>item 3</li>
        <ul>
            <li>Item 3.1</li>
            <li>Item 3.2</li>
            <li>Item 3.3</li>
        </ul>
    <li>item 4</li>
    <li>Item 5</li>
        <ul>
            <li>Item 5.1</li>
            <li>Item 5.2</li>
            <li>Item 5.3</li>
        </ul>
    <li>item 6</li>
</ul>

I would like to be able to sort through them, after they are created, so that any item that has a sublist(for example item 3 & item 5) will go to the top of the list, for output like this: 创建它们后,我希望能够对它们进行排序,以便具有子列表的任何项目(例如,项目3和项目5)都将转到列表的顶部,以进行如下输出:

<ul>
    <li>item 3</li>
        <ul>
            <li>Item 3.1</li>
            <li>Item 3.2</li>
            <li>Item 3.3</li>
        </ul>
    <li>Item 5</li>
        <ul>
            <li>Item 5.1</li>
            <li>Item 5.2</li>
            <li>Item 5.3</li>
        </ul>
    <li>item 1</li>
    <li>item 2</li>
    <li>item 4</li> 
    <li>item 6</li>
</ul>

I am thinking I can do this with jQuery or the javascript .sort() method but I'm not sure where to go with it. 我想我可以使用jQuery或javascript .sort()方法来执行此操作,但是我不确定该在哪里使用。 Any advice? 有什么建议吗?

Firstly you should put your sublists inside their parent element and give a class to your list, like this: 首先,您应该将子列表放入其父元素内,并为列表提供一个类,如下所示:

<ul class="autoReorder">
   <li>item 1</li>
   <li>item 2</li>
   <li>item 3
      <ul>
         <li>Item 3.1</li>
         <li>Item 3.2</li>
         <li>Item 3.3</li>
      </ul>
   </li>
   <li>item 4</li>
   <li>Item 5
      <ul>
         <li>Item 5.1</li>
         <li>Item 5.2</li>
         <li>Item 5.3</li>
      </ul>
   </li>
   <li>item 6</li>
</ul>

Then in jQuery here is your solution: 然后在jQuery中,这是您的解决方案:

$(document).ready(function(){
   $('ul.autoReorder').find('li ul').parent().prependTo('ul.autoReorder');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM