问题
I am trying to convert the following 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>
to the following bbCode
[quote=Joe Block]
This is the first message
[quote=Jane Doe]
This is the second message
[/quote]
[/quote]
How can I do this using jQuery?
PS: Nested HTML can have zero or more children
回答1:
Here's a very basic example:
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();
Fiddle
Limitations:
- It won't convert other HTML to BBCode (
<b>
,<i>
, anchor tags etc); - Indentation/white space is not 100% accurate.
I'd use Ajax to fetch the actual post content from the DB or use a proper jQuery bbCode parsing library.
来源:https://stackoverflow.com/questions/12519688/converting-nested-html-to-bbcode-quote-tags