JQuery删除不删除空列表元素

时间:2013-04-30 08:45:32

标签: javascript jquery

我编写了以下方法来展平嵌套列表的深层次结构(我使用的是TypeScript,但是你得到了JS的想法)。

该方法针对每个顶级<li>元素运行,以便在其自身之后插入其所有后代<li>

    // Flatten a nested list branch - acts in reverse to allow for nested lists
    _flattenBranch(element: HTMLElement)
    {
        var el = $(element);
        $(el.find('li').get().reverse()).each(function ()
        {
            el.after(this);
        });
        // FIX: This is not removing empty descendant lists!
        el.find('ul').remove();
    }

我注意到在查看生成的输出时,我在某些<ul></ul>下仍然有空<li>秒。我错过了什么?

更新(和重复):

试试这个jsfiddle:http://jsfiddle.net/3gu7L/3/

导致输出中出现以下错误:

<li>Application Form
    <ul>
    </ul>
</li>

- 如果使用以下内容调用Arun P Johny的{​​{3}}(与我的代码类似),则会展平层次结构,但无法删除某些元素上的子<ul>

$('#test').children('li').each(function(){
    test(this)
});

1 个答案:

答案 0 :(得分:0)

这是一个简单的解决方案,但前提是你有3个级别的列表:

function test(element){
    var el = $(element);
    $(el.find('li').get().reverse()).each(function () {
        el.after(this);
        $(this).find('ul').remove();
    });
    // FIX: This is not removing empty descendant lists!
    el.find('ul').remove();
}
$('#test').children('li').each(function(){
    test(this)
});

在您的示例中,您尝试在主页的子级中找到所有<ul>,但申请表不再是主页的子级>

相关问题