我想转换下面的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>
以下设置高亮
[quote=Joe Block]
This is the first message
[quote=Jane Doe]
This is the second message
[/quote]
[/quote]
我怎样才能做到这一点使用jQuery?
PS:嵌套HTML可以有零个或更多孩子
这里是一个非常简单的例子:
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();
小提琴
限制:
- 它不会其他HTML转换成BB代码(
<b>
<i>
锚标签等); - 压痕/白色空间不是100%准确。
我使用Ajax来获取从DB实际帖子内容或使用适当的jQuery BBCode的解析库。