使用jquery在特定标记之前和之后向文本添加包装标记 [英] adding wrapping tags to text before AND after a specific tag with jquery
问题描述
我正在尝试在包含段落和中断标记的重复html块上创建详细信息和摘要标记结构。
I am trying to create a details and summary tag structure on repeating blocks of html that include paragraphs and break tags.
我的div有一个特定的类,我想要使用jquery查找内容。具体来说,分配给我的css类的每个段落的第一个中断标记将用作标记,第一个中断之前的所有内容都被< summary>< / summary>
标签和整个匹配段落中的所有内容都包含一个标签对。
My divs have a specific class and I want to use jquery to find content with. Specifically the first break tag of each paragraph assigned to my css class would be used as a marker, with everything before the first break being wrapped by <summary></summary>
tags and everything within the entire matching paragraph to be inner wrapped with a tag pair.
所以给出一个前后html的例子。在更改之前,它看起来像这样......
So to give an example of the html before and after. Before the change it would look like this...
<p class="matchingClass">
this should be in a summary<br>this would be within the expandable details tag
</p>
它最终应该像......
And it should end up like...
<p class="matchingClass"><details><summary>
this should be in a summary</summary><br>this would be within the expandable details tag
</details></p>
我以为我使用了以下代码....
I thought I had this working with the following code....
$(".matchingClass").each(function() {
$(this).prepend("<details><summary>");
$(this).find("br").first().before().prepend("</summary>");
$(this).append("</details>");
});
但我现在意识到jquery / javascript总是自动插入结束标记。因此,只要我应用的3个命令中的第一个运行,html就不会结束我的预期。
BUT i now realise that jquery/javascript always inserts closing tags automatically. So as soon as the first of the 3 commands I apply runs the html doesn't end up how I expected it.
有人可以帮忙吗?
推荐答案
DEMO: http://jsfiddle.net/RJktH/
$('.matchingClass').each(function () {
var t = $(this).html();
$(this).html('<summary>' + t.replace('<br>', '</summary>'));
});
$('.matchingClass').wrapInner('<details/>');
这篇关于使用jquery在特定标记之前和之后向文本添加包装标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!