jquery - 将 li 元素移出父 ul 并保留位置

标签 jquery dom element

我需要将 li 元素从其父 ul 移出并移入主父 ul。

我尝试过这个:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script type="text/javascript">

$( init );

function init() {

 // Move
  $('ul#listcomments').append( $('.children>li') );
  // Delete
  $('.children').remove();
}

</script>

</head>
<body>



<ul id="listcomments">
<li>Comment 1</li>
<li>Comment 2</li>
<li>Comment 3</li>
<li>Comment 4</li>
<li>Comment 5 <ul class="children"><li>Child comment of #5 is this</li></ul></li>
<li>Comment 6</li>
<li>Comment 7</li>
<li>Comment 8</li>
</ul>

</body>
</html>

我想实现这个目标: * 即让child li#5child脱离ul和li,出现在li的正下方。

<ul id="listcomments">
<li>Comment 1</li>
<li>Comment 2</li>
<li>Comment 3</li>
<li>Comment 4</li>
<li>Comment 5</li>
<li>Child comment of #5 is this</li>
<li>Comment 6</li>
<li>Comment 7</li>
<li>Comment 8</li>
</ul>

相反,我得到: * add 将 li 放在外面,但将其放在 ul#listcomments 的最末尾

<ul id="listcomments">
<li>Comment 1</li>
<li>Comment 2</li>
<li>Comment 3</li>
<li>Comment 4</li>
<li>Comment 5 </li>
<li>Comment 6</li>
<li>Comment 7</li>
<li>Comment 8</li>
<li>Child comment of #5 is this</li>
</ul>

我希望这比使用文字更好地解释它。作为一个概念,它非常简单,但由于我的技能有限,我无法想出更好的东西。

救命啊! :)

*注意:lis 的命名和编号是任意的。并且子评论可以出现在任意#li 内。内容是动态生成的。

最佳答案

试试这个:

<script type="text/javascript">
$( init );

function init() {
    $('.children').each(function() {
        // save
        $a=$(this).children('li');
        // Move
        $($a.parent().parent()).after($a);
        // Delete
        $(this).remove();
    });
}
</script>

无论存在多少个 ul 子元素,也无论它们有多少个 li 子元素,这都会解决您的问题。

关于jquery - 将 li 元素移出父 ul 并保留位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7538589/

相关文章:

jquery - 当鼠标悬停时更改多个 div 的类

javascript - 用 span 替换 #text 元素会导致文档 reshape

javascript - 尝试在控制台中选择所有指向特定 DOM 事件的链接。我去那里的路还好吗?

jQuery ready 在点击链接后不起作用

jquery - 使用 jQuery 将连续的列表项包装在单独的组中

javascript - 使用jquery从右到左显示分钟刻度

javascript - jQuery Mobile : $. 移动未定义

jquery - 如何选择最小的数?

jquery - 访问backbone.js-events上的当前元素?

javascript - 我的猜测次数不会停止在正确的水平