且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从简单列表创建下拉菜单

更新时间:2022-05-25 02:42:23

您可以使用以下逻辑来实现所需的效果.

You can achieve the effect you're looking for by using the following logic.

  1. 创建一个公共缓存变量以保存上一个***菜单.
  2. 浏览所有菜单列表项,以检查文本是否以下划线开头.
    • 如果有,请将其附加到上一个顶层菜单.
    • 如果没有,请向此列表项添加一个新的无序列表元素,并将新列表缓存在上一个***菜单变量中.
  1. Create a common cache variable to hold the previous top-level menu.
  2. Loop through all menu list items checking to see whether the text begins with an underscore.
    • If it does, append this to the previous top-level menu.
    • If it does not, append a new unordered list element to this list item and cache the new list in the previous top-level menu variable.

在下面的示例中,在某些情况下,我偏爱本机DOM API方法而不是jQuery对应的方法,因为:

In the example below I have favoured Native DOM API methods instead of their jQuery counterparts in a few instances because:

  1. $(this).append('<ul></ul>')返回$(this),而不是新创建的列表.解决方法是添加另一行代码,或者仅使用DOM API this.appendChild($('<ul>')[0])来返回新创建的列表.还有...
  2. 在使用DOM API一样简单的情况下,使用jQuery似乎很浪费. 请参阅: youmightnotneedjquery.com
  1. $(this).append('<ul></ul>') returns $(this) instead of the newly created list. The work around is to add another line of code, or just use the DOM API this.appendChild($('<ul>')[0]) which does return the newly created list. And...
  2. It just seems wasteful to use jQuery in situations where it is just as simple to use the DOM API. see: youmightnotneedjquery.com

var prev;
$('.menu li').each(function(){
    if(/^_/.test(this.textContent) && prev) {
        prev.appendChild(this);
    } else {
        prev = this.appendChild($('<ul>')[0]);
    }
}).find('ul:empty').remove();

<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<ul class="menu">
   <li><a href="#">Menu 1</a></li>
   <li><a href="#">_Submenu a</a></li>
   <li><a href="#">_Submenu b</a></li>
   <li><a href="#">_Submenu c</a></li>
   <li><a href="#">Menu 2</a></li>
   <li><a href="#">Menu 3</a></li>
   <li><a href="#">_Submenu x</a></li>
   <li><a href="#">_Submenu y</a></li>
   <li><a href="#">Menu 4</a></li>
</ul>

上面的示例产生以下HTML结构:

The example above results in the following HTML structure:

<ul class="menu">
    <li><a href="#">Menu 1</a>
        <ul>
            <li><a href="#">_Submenu a</a></li>
            <li><a href="#">_Submenu b</a></li>
            <li><a href="#">_Submenu c</a></li>
        </ul>
    </li>
    <li><a href="#">Menu 2</a></li>
    <li><a href="#">Menu 3</a>
        <ul>
            <li><a href="#">_Submenu x</a></li>
            <li><a href="#">_Submenu y</a></li>
        </ul>
    </li>
    <li><a href="#">Menu 4</a></li>
</ul>