Creating dropdown menu from simple list

后端 未结 3 976
时光取名叫无心
时光取名叫无心 2021-01-06 12:18

I have current list look like:

3条回答
  •  悲&欢浪女
    2021-01-06 12:30

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

    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.
    3. Once the loop has finished you can select all lists that are empty and remove them (.find('ul:empty').remove()).

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

    1. $(this).append('
        ')
        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($('
          ')[0]) which does return the newly created list. And...
        • 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($('
        ')[0]); } }).find('ul:empty').remove();
      
      

      The example above results in the following HTML structure:

      
      

    提交回复
    热议问题