JQuery добавить элемент в каждом цикле - PullRequest
0 голосов
/ 25 июня 2019

Получаю небольшую головную боль с jQuery при попытке добавить кнопку переключения для каждого элемента, который содержит определенный класс.Поскольку я использую jQuery .each(, я надеялся сделать это в цикле, я добавил свой класс идентификатора.Но почему-то он продолжает добавлять мой HTML-код в цикле к каждому li вместо li.has-children

Это мой текущий код:

    function addLevelClass($parent, level) {
      // fetch all the li's that are direct children of the ul
      var $children = $parent.children('li');
      // loop trough each li
      $children.each(function() {
        // get the ul that is a direct child of the li
        var $sublist = $(this).children('ul');
        // if an ul was found
        if ($sublist.length > 0) {
          $sublist.addClass('slideable-submenu');
          // add a class to the current li indicating there is a sub list
          $(this).addClass('has-children level-'+level);


          //last attempt before ask on SO
          if( $(this).hasClass('has-children level-'+level) ){
            $( 'li.has-children span a' ).after( '<span class="sub-menu-toggle"></span>');
          }

          // repeat the process for the sublist, but with the level one higher
          // = recursive function call
          addLevelClass($sublist, level+1);
        }
      });
    }

    // call the function to add level classes on the upper most ul
    addLevelClass($('.header-mobile-menu'), 0);
    //$( 'li.has-children span a' ).after( '<span class="sub-menu-toggle"></span>');//Adds toggle buttons everywhere

Так что идея состоит в том, чтобы получить:

$( 'li.has-children span a' ).after( '<span class="sub-menu-toggle"></span>');

В правильном положении.

1 Ответ

1 голос
/ 25 июня 2019

Если я правильно понимаю, вы пытаетесь добавить кнопку переключения с каждым <li>, у которого есть подменю.

Если это так, я создал скрипку с некоторой общей разметкой, которая может оказаться полезной.

Единственным реальным изменением, которое я сделал, было добавление кнопки переключения, и я удалил рекурсивный вызов самому себе.

Вот обновленный код:

function addLevelClass($parent, level) {

      // fetch all the li's that are direct children of the ul
      var $children = $parent.children('li');

      // loop trough each li
      // here I added a check if level is defined, if not set it to 0, this way you don't have to pass it a value unless you want to start it somewhere
      var level = (typeof(level) !== 'undefined') ? level : 0;
      $children.each(function() {
        // get the ul that is a direct child of the li
        var $sublist = $(this).children('ul');
        // if an ul was found
        if ($sublist.length > 0) {


          $sublist.addClass('slideable-submenu');

          // add a class to the current li indicating there is a sub list
          $(this).addClass('has-children level-'+level).find('span:first').append( '<span class="sub-menu-toggle">toggle</span>');

          // increment level
          level++;

        }
      });
    }

    // call the function to add level classes on the upper most ul
    addLevelClass($('#parent ul'));
    //$( 'li.has-children span a' ).after( '<span class="sub-menu-toggle"></span>');//Adds toggle buttons everywhere
...