首页 > 解决方案 > jQuery在每个循环中添加元素

问题描述

在我尝试为每个包含特定类的元素添加一个切换按钮时,我对 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>');

在正确的位置。

标签: jqueryeach

解决方案


如果我理解正确,您正在尝试添加一个切换按钮,每个按钮<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

推荐阅读