jQuery   发布时间:2022-04-19  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了jquery – 替换元素中的内容而不替换HTML大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
假设我有以下 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>

基本上,我想在整个元素中替换,但保留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),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,请注明来意。