从parent中移除一个子节点,并将其添加为Sibling到parent
Remove a child from parent and add it as Sibling to Parent
我有一个项目符号区域
- 你好
- 如何
- 是
- 你
不,我选择
- 你好
- 如何
- 是
- 你
- 想要在第二个孩子之后结束Disc子弹。
- 要添加第三个子作为父级的兄弟姐妹。
- 想再次将Disc bullet作为第四个子元素,并将其作为兄弟元素添加到父元素。
这实际上是一个非常重要且非常有趣的问题。但是,您首先需要知道几件事:
- 列表项上的符号由其列表决定;
ul
用于无序列表(即。磁盘子弹),ol
用于有序列表(即。编号的子弹)。 - 你不能有
li
没有其父ul
或ol
。 - 你不能让
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/
代码绝对可以优化速度/性能,但我的目标是简单和清晰,我希望我能做到这一点。
相关文章:
- jQuery parent() in table
- iFrame parent node
- Javascript TypeError:$(..)parent不是函数
- parent和iframe中的Bootstrap.js文件
- 如何捕获jqueryDialog和Parent之间的交互
- 如何从DOM(KnockoutJS)中删除$data、$parent等
- 在angular中使用$parent是一种好的做法吗
- 从 Childe 到 Parent ASP 的变量
- this.constructor.apply vs this.parent.apply
- 在JQuery中使用parent()和children()方法的缺点
- 如何在jquery中创建函数和parent.function
- jQuery parent或parents以获取表th标记中的数据属性
- Window.parent and Window.top returning null
- jQuery:如何正确选择parent.prev
- Parent() UL of div
- positon元素相对于JS中的parent.part容器?没有绝对/固定的定位
- jQuery parent.sibling logic
- 将jQuery的parent()和sibling()调用转换为纯Javascript
- jQuery导航-更改input parent-parent-parent-parent-sibling的输入
- 从parent中移除一个子节点,并将其添加为Sibling到parent