从父级中删除子项并将其添加为父级的兄弟

时间:2013-03-05 04:45:50

标签: javascript

我有像

这样的子弹区域
  • 您好
  • 如何

不,我选择

  • 并更改为Number Bullet。 所以我的列表应该像

    一样改变

    • 你好
    • 如何

      1. 想要在第二个孩子之后结束Disc子弹。
      2. 希望将第三个孩子添加为父母的兄弟姐妹。
      3. 想要再次将Disc子弹制作给第四个孩子并将其作为兄弟姐妹添加到父母身上。
      4. 我该怎么做。

    1 个答案:

    答案 0 :(得分:0)

    这实际上是一个非常重要且非常有趣的问题。但是,您需要先了解一些事情:

    1. 列表项上的项目符号由其列表确定; ul用于无序列表(即磁盘子弹),ol用于有序列表(即编号子弹)。
    2. 如果父母不是liul,则不能ol
    3. 你不能让ul成为ol的直接孩子,反之亦然(他们可能是li的孩子,但他们将成为子列表)
    4. 这意味着每次切换列表时,都需要确保正在切换的项目具有正确(和相反)类型的父项,并且它之前和之后的项目也在(单独)正确类型的列表。在许多情况下,您将需要创建这些列表(或在它们变空时删除它们)。

      无论如何,单词是毫无价值的,这是代码(我使用的是jQuery,但无论你使用什么,这个想法应该是一样的):

      $('li').on('click', function () { 
          var $listItem = $(this);
          var $list     = $(this).parent();
          var $items    = $list.children();
          var itemIndex = $items.index($listItem);
          var numItems  = $items.length;
      
          var curType = $list.is('ul')   ? 'ul' : 'ol';
          var newType = curType === 'ul' ? 'ol' : 'ul';
      
          var $prev = $list.prev();
          var $next = $list.next();
      
          if (itemIndex === 0) {
              // The item we're switching is the first Item in the list
              if (!$prev.is(newType)) {
                  $prev = $('<' + newType + '/>');
                  $prev.insertBefore($list);
              }
              $prev.append($listItem);
          } else if (itemIndex === numItems - 1) {
              // The item we're switching is the last Item in the list
              if (!$next.is(newType)) {
                  $next = $('<' + newType + '/>');
                  $next.insertAfter($list);
              }
              $next.prepend($listItem);
          } else {
              // The item is in the middle, we need to split the current list into 3.
              $tailList = $('<' + curType + '/>');
              $tailList.append($listItem.nextAll());
              $tailList.insertAfter($list);
      
              $middleList = $('<' + newType + '/>');
              $middleList.append($listItem);
              $middleList.insertAfter($list);
          }
      
          if (numItems === 1) {
              // list used to have only one Item, so it's now empty, and should be removed.
              $list.remove();
      
              if ($prev.is(newType) && $next.is(newType)) {
                  // The two surrounding lists are of the same type and should be merged.
                  $prev.append($next.children());
                  $next.remove();
              }
          }
      });
      

      我正在使用列表项上的click事件来切换列表项。这里有一个jsFiddle链接供您使用实现并验证一切正常工作:http://jsfiddle.net/8Z9rf/

      代码绝对可以针对速度/性能进行优化,但我的目标是简单明了,我希望我能够实现这一目标。

    相关问题