2

我正在尝试转换以下html

<div class="bbQuote">
    <div class="quoteAuthor">Joe Block</div>
    <div class="quoteContent">This is the first message<br>
        <div class="bbQuote">
            <div class="quoteAuthor">Jane Doe</div>
            <div class="quoteContent">This is the second message</div>
        </div>
    </div>
</div>

到下面的bbCode

[quote=Joe Block]
    This is the first message
    [quote=Jane Doe]
        This is the second message
    [/quote]
[/quote]

如何使用 jQuery 做到这一点?

PS:嵌套的 HTML 可以有零个或多个孩子

4

1 回答 1

2

这是一个非常基本的示例:

var html = $('#commentContent').html(),
    beingParsed = $('<div>' + html.replace(/<br>/g, '\n\r') + '</div>'),
    $quote;
while (($quote = beingParsed.find('.bbQuote:first')).length) {
    var $author = $quote.find('.quoteAuthor:first'),
        $content = $quote.find('.quoteContent:first'),
        toIndent = $author[0].previousSibling;

    toIndent.textContent = toIndent.textContent.substring(0, toIndent.textContent.length-4);
    $author.replaceWith('[quote=' + $author.text() + ']');
    $content.replaceWith($content.html());
    $quote.replaceWith($quote.html() + '[/quote]');
}

var parsedData = beingParsed.html();

小提琴

限制:

  1. 它不会将其他 HTML 转换为 BBCode(<b>、、<i>锚标记等);
  2. 缩进/空白不是 100% 准确的。

我会使用 Ajax 从数据库中获取实际的帖子内容或使用适当的 jQuery bbCode 解析库。

于 2012-09-20T21:22:48.180 回答