限制给定 html 字符串上的标记深度

Limit tag depth on given html string

本文关键字:深度 字符串 html      更新时间:2023-09-26

我在SO上看了一段时间,找不到答案。

假设我在 html 字符串中有一组嵌套标签:

<blockquote>
    <blockquote>
        <blockquote>
            <blockquote>
                Some Text 1
            </blockquote>
            Some Text 2
        </blockquote>
    Some Text 3
    </blockquote>
    <blockquote>
    Text!
        <blockquote>
        Text 2!
        </blockquote>
    </blockquote>
Some Text 4
</blockquote>

在 jquery 中,我如何获取该 html 字符串并将其转换为另一个 html 字符串,但删除第 n 个嵌套块引用。因此,如果我将其限制为两个,这将保留:

<blockquote>
    <blockquote>
    Some Text 3
    </blockquote>
    <blockquote>
    Text!
    </blockquote>
Some Text 4
</blockquote>

最好是函数的原型应如下所示:

var limit = 2;
myHtmlString = limitQuotes(myHtmlString, limit);

关于此事的任何指示都会有所帮助。

根据Doge的评论:

function limitQuotes(html, max_depth){
    var depth_selector = '';
    for(var i = 0; i < max_depth; i++){
        depth_selector += '>blockquote';
    }
    html = $(html);
    html.find(depth_selector).remove();
    return html.wrap('<p>').parent().html();
}
$('body').html(limitQuotes('<blockquote><blockquote><blockquote><blockquote>Some Text 1</blockquote>Some Text 2</blockquote>Some Text 3</blockquote><blockquote>Text!<blockquote>Text 2!</blockquote></blockquote>Some Text 4</blockquote>',2));

http://jsfiddle.net/AA67d/6/

注意:更适合的变量名称会有所帮助。