2012-09-20 32 views
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> 

转换下面的HTML到以下bbcode

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

我怎样才能做到这一点使用jQuery?

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

+0

HTML是在页面还是字符串?在我认为的页面中? –

+0

HTML使用'jQuery('#commentContent')。html()'解析,因此它可以是html或文本。 – Optimus

+2

我做了一个你想要的东西 - [小提琴](http://jsfiddle.net/ult_combo/tE77x/)的原始示例,但它不会转换其他bbCode标签([b],[i],定位标签等等),2.缩进不相同。我会使用ajax从数据库中获取实际的发布内容或使用合适的jQuery bbCode解析库。 –

回答

1

这里是一个非常简单的例子:

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

限制:

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

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