代码之家  ›  专栏  ›  技术社区  ›  Propeng

使用jQuery将列表项(li)分组到OLs/ULs

  •  0
  • Propeng  · 技术社区  · 16 年前

    是否可以使用Javascript和jQuery或正则表达式在HTML中对多个同级列表项进行分组,如下面的示例所示?我需要将TikiWiki标记转换为HTML,并且它使用未分组的列表(只是在相邻的行中加上#)。

    <li>Item 1.1</li>
    <li>Item 1.2</li>
    <li>Item 1.3</li>
    <p>Paragraph</p>
    <li>Item 2.1</li>
    <li>Item 2.2</li>
    

    <ul>
    <li>Item 1.1</li>
    <li>Item 1.2</li>
    <li>Item 1.3</li>
    </ul>
    <p>Paragraph</p>
    <ul>
    <li>Item 2.1</li>
    <li>Item 2.2</li>
    </ul>
    

    我已经试过了 $("li").wrapAll() siblings() . 两个都失败了。

    replace(/[#](.*)\n?/g, "<li class='numbered'>$1</li>") replace(/repeat([#](.*)\n?)/g, "<ol>foreach(<li class='numbered'>$1</li>)</ol>")

    2 回复  |  直到 16 年前
        1
  •  0
  •   Sage    16 年前

        <div id='testList'>
            <li>Item 1.1</li>
            <li>Item 1.2</li>
            <li>Item 1.3</li>
            <p>Paragraph</p>
            <li>Item 2.1</li>
            <li>Item 2.2</li>
    
        </div>
    
    <script language='javascript' type='text/javascript'>
    
    $.fn.tagName = function() {
        return this.get(0).tagName;
    }
    
    $(document).ready(function() {
    
        alert($("#testList").html());
    
        $("li").each(function() {
            if ( $(this).parent().tagName() != "UL" ) {
                $(this).wrap("<ul></ul>");
                // alert($(this).parent().tagName())
            }
        })
    
        alert($("#testList").html());
    });
    </script>
    
        2
  •  0
  •   Ken Redler    16 年前

    这个 <p> 只是在一群人中间闲逛 <li>s ,表示组的开始或结束?也许是这样的:

    ​$('div#container') // assume you're got it in a container div
      .find('p').each( function(){ // each p signifies a new group
        $(this)
          .prev('li') // walk back to the preceding li
          .prevUntil('p') // get the set of elements up to the previous p
          .andSelf() // include the current li
          .wrapAll('<ul>');​​​​​​​​​​​​​​​​​​​​​​​​​​ // wrap the set in a ul
       });
    

    这里有一个 working jsFiddle 使用这种方法。