gpt4 book ai didi

jquery - 将嵌套 html 转换为 bbCode 引用标签

转载 作者:行者123 更新时间:2023-12-01 04:58:26 26 4
gpt4 key购买 nike

我正在尝试转换以下 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 可以有零个或多个子级

最佳答案

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

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> 、 anchor 标记等);
  2. 缩进/空格并非 100% 准确。

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

关于jquery - 将嵌套 html 转换为 bbCode 引用标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12519688/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com