从parent中移除一个子节点,并将其添加为Sibling到parent

Remove a child from parent and add it as Sibling to Parent

本文关键字:parent Sibling 子节点 添加 一个      更新时间:2023-09-26

我有一个项目符号区域

  • 你好
  • 如何

不,我选择

  • ,并更改为数字子弹头。所以我的列表应该改成

    • 你好
    • 如何
    1. 想要在第二个孩子之后结束Disc子弹。
    2. 要添加第三个子作为父级的兄弟姐妹。
    3. 想再次将Disc bullet作为第四个子元素,并将其作为兄弟元素添加到父元素。

    这实际上是一个非常重要且非常有趣的问题。但是,您首先需要知道几件事:

    1. 列表项上的符号由其列表决定;ul用于无序列表(即。磁盘子弹),ol用于有序列表(即。编号的子弹)。
    2. 你不能有li没有其父ulol
    3. 你不能让ul成为ol的直接子节点,反之亦然(它们可以是li的子节点,但是它们将是子列表)

    这意味着每次切换列表时,您都需要确保要切换的项具有正确(相反)类型的父项,并且它之前和之后的项也位于正确类型的(单独的)列表中。在许多情况下,您将需要创建这些列表(或者在它们变为空时删除它们)。

    无论如何,文字是毫无价值的,下面是代码(我使用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/

    代码绝对可以优化速度/性能,但我的目标是简单和清晰,我希望我能做到这一点。