jQuery在每个循环中添加元素

时间:2019-06-25 15:52:42

标签: jquery each

在尝试向包含特定类的每个元素添加切换按钮时,让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 个答案:

答案 0 :(得分:1)

如果我正确理解,您正在尝试为每个具有子菜单的<li>添加一个切换按钮。

如果是这样,我创建了一个带有一些通用标记的fiddle

我所做的唯一真正的更改是附加了切换按钮的方式,并删除了对其自身的递归调用。

这是更新的代码:

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