Javascript JQuery替换div中除标记以外的所有内容
我必须替换所有div中的一些字符,但是当我运行代码时,该函数也会替换我的html标记字符 我的代码是:Javascript JQuery替换div中除标记以外的所有内容,javascript,jquery,html,Javascript,Jquery,Html,我必须替换所有div中的一些字符,但是当我运行代码时,该函数也会替换我的html标记字符 我的代码是: $("#main").children().each(function() { $(this).html($(this).html().replace(/s/g, "K")); }) <div id="main"> <p>Some contents that will be replaced... <span>this will not be in
$("#main").children().each(function() {
$(this).html($(this).html().replace(/s/g, "K"));
})
<div id="main">
<p>Some contents that will be replaced... <span>this will not be in a span tag :(</span></p>
</div>
$(“#main”).children().each(function()){
$(this.html($(this.html().replace(/s/g,“K”)));
})
将被替换的某些内容。。。这将不在范围标记中:(
结果:
<div id="main">
<p>Kome contentK that will be replaced... <Kpan>this will not be in a Kpan tag :(</Kpan></p>
</div>
将被替换的Kome contentK…这不在Kpan标签中:(
如果您的目标是保留div中的所有标记,但替换所有这些标记中的文本,这是很困难的。您需要只找到文本节点,而不找到其他节点,并在每个文本节点中分别进行替换
这个问题可能有助于: