TVA*_*ren 6 html jquery replace preserve
假设我有以下HTML结构:
<test>
<div>
This is a test
</div>
<div>
This is another test
<button>
Button test
</button>
</div>
</test>
Run Code Online (Sandbox Code Playgroud)
现在我使用以下jQuery代码替换,例如'T':
$("test *").each(function(index, value) {
$(this).html($(this).html().replace(new RegExp('t', "ig"), "<b>t</b>"));
});
Run Code Online (Sandbox Code Playgroud)
但是,这会产生以下HTML结构(这是意料之外的,请参阅<button>标记,这会破坏我的HTML):
<test>
<div>
<b>T</b>his is a <b>t</b>es<b>t</b>
</div>
<div>
<b>T</b>his is ano<b>t</b>her <b>t</b>es<b>t</b>
<bu<b>t</b><b>t</b>on>
Bu<b>t</b><b>t</b>on <b>t</b>es<b>t</b>
</bu<b>t</b><b>t</b>on>
</div>
</test>
Run Code Online (Sandbox Code Playgroud)
我想要实现的是:
<test>
<div>
<b>T</b>his is a <b>t</b>es<b>t</b>
</div>
<div>
<b>T</b>his is ano<b>t</b>her <b>t</b>es<b>t</b>
<button>
Bu<b>t</b><b>t</b>on <b>t</b>es<b>t</b>
</button>
</div>
</test>
Run Code Online (Sandbox Code Playgroud)
基本上,我想在整个元素中替换,但保留HTML标记和所有HTML属性.
使用 jQuery,这可以相当简单地实现。创建一个函数,该函数接受您希望更新其文本的元素、您希望替换的文本以及您希望替换的内容。然后,在该函数中,您想要删除子 HTML 并使用替换文本更新元素中剩余的任何文本。然后,您可以为每个子元素递归运行相同的函数,然后将它们附加回父元素。
function replaceTextInHtmlBlock($element, replaceText, replaceWith)
{
var $children = $element.children().detach();
//Now that there should only be text nodes left do your replacement
$element.html($element.text().replace(replaceText, replaceWith));
//Run this function for each child element
$children.each(function(index, me){
replaceTextInHtmlBlock($(me), replaceText, replaceWith);
});
$element.append($children);
}
$(document).ready(function(){
$("#doReplace").click(function(){
replaceTextInHtmlBlock($("#top"), $("#replace").val(), $("#with").val());
});
});Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="top">
<div>
This is a test
</div>
<div>
This is another test
<button>
Button test
</button>
</div>
</div>
<br />
<br />
<div>
<label>Replace</label>
<input id="replace" value="t" />
<label>with</label>
<input id="with" value="<strong>t</strong>" />
<button id="doReplace">Do Replace</button>
</div>Run Code Online (Sandbox Code Playgroud)