我有一个像这样的项目符号区域
- 你好
- 你好吗
- 你好吗
- 你好吗
不,我正在选择
- 你好
- 怎么样
- 是
- 你
- 想要在生第二个 child 后结束 Disc 子弹。
- 想要将第三个 child 添加为 parent 的 sibling 。
- 想要再次将 Disc 项目符号添加到第四个子级并将其添加为父级的兄弟级。
我该怎么做。
最佳答案
这实际上是一个不平凡且非常有趣的问题。但是,您首先需要了解一些事情:
- 列表项上的项目符号由其列表确定;
ul
用于无序列表(即磁盘项目符号),ol
用于有序列表(即编号项目符号)。 - 如果
li
的父级不是ul
或ol
,则不能拥有li
。 - 您不能让
ul
成为ol
的直接子级,反之亦然(尽管它们可以是li
的子级,但是那么它们将是子列表)
这意味着每次切换列表时,您都需要确保要切换的项目具有正确(且相反)类型的父级,并且其之前和之后的项目也在(单独的)中正确类型的列表。在许多情况下,您需要创建这些列表(或在它们变空时将其删除)。
无论如何,文字是没有值(value)的,这是代码(我使用的是 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();
}
}
});
我正在使用列表项上的单击事件来切换列表项。这是一个 jsFiddle 链接,供您尝试实现并验证一切是否按预期工作:http://jsfiddle.net/8Z9rf/
代码绝对可以针对速度/性能进行优化,但我的目标是简单和清晰,我希望我能够实现这一点。
关于javascript - 从父级中删除子级并将其添加为父级的兄弟级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15216016/