>我正在尝试转换以下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>
到以下 bb代码
[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, 'nr') + '</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转换为BBCode(
<b>
,<i>
,锚标签等); - 缩进/空格不是 100% 准确的。
我会使用 Ajax 从数据库中获取实际的帖子内容,或者使用适当的 jQuery bbCode 解析库。