大佬教程收集整理的这篇文章主要介绍了jquery – 替换元素中的内容而不替换HTML,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
<test> <div> This is a test </div> <div> This is another test <button> Button test </button> </div> </test>
现在我使用以下jQuery代码替换,例如’T’:
$("test *").each(function(index,value) { $(this).html($(this).html().replace(new RegExp('t',"ig"),"<b>t</b>")); });
但是,这会产生以下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>
我想要实现的是:
<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>
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),replaceWith); }); $element.append($children); } $(document).ready(function(){ $("#doreplace").click(function(){ replaCETexTinHtmlBlock($("#top"),$("#replace").val(),$("#with").val()); }); });
<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>
以上是大佬教程为你收集整理的jquery – 替换元素中的内容而不替换HTML全部内容,希望文章能够帮你解决jquery – 替换元素中的内容而不替换HTML所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。