jQuery 替换 html 页面中所有出现的字符串 [英] jQuery replace all occurrences of a string in an html page
本文介绍了jQuery 替换 html 页面中所有出现的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在做一个项目,我需要用另一个字符串替换所有出现的字符串.但是,如果它是文本,我只想替换字符串.比如我想转这个...
<h1>Hi</h1><h2 class="Hi">测试</h2>你好
进入...
<h1>你好</h1><h2 class="Hi">测试</h2>你好
在那个例子中,除了作为 h2 类的Hi"之外,所有的Hi"都变成了Hello".我试过了...
$("#container").html( $("#container").html().replace(/Hi/g, "Hello" ) )
... 但这也替换了 html 中所有出现的Hi"
解决方案
这个:
$("#container").contents().each(function () {if (this.nodeType === 3) this.nodeValue = $.trim($(this).text()).replace(/Hi/g, "Hello")if (this.nodeType === 1) $(this).html( $(this).html().replace(/Hi/g, "Hello") )})
产生这个:
<h1>你好</h1><h2 class="Hi">测试</h2>你好
I'm working on a project where I need to replace all occurrences of a string with another string. However, I only want to replace the string if it is text. For example, I want to turn this...
<div id="container">
<h1>Hi</h1>
<h2 class="Hi">Test</h2>
Hi
</div>
into...
<div id="container">
<h1>Hello</h1>
<h2 class="Hi">Test</h2>
Hello
</div>
In that example all of the "Hi"s were turned into "Hello"s except for the "Hi" as the h2 class. I have tried...
$("#container").html( $("#container").html().replace( /Hi/g, "Hello" ) )
... but that replaces all occurrences of "Hi" in the html as well
解决方案
This:
$("#container").contents().each(function () {
if (this.nodeType === 3) this.nodeValue = $.trim($(this).text()).replace(/Hi/g, "Hello")
if (this.nodeType === 1) $(this).html( $(this).html().replace(/Hi/g, "Hello") )
})
Produces this:
<div id="container">
<h1>Hello</h1>
<h2 class="Hi">Test</h2>
Hello
</div>
这篇关于jQuery 替换 html 页面中所有出现的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文