jQuery替换html页面中所有出现的字符串 [英] jQuery replace all occurrences of a string in an html page

查看:140
本文介绍了jQuery替换html页面中所有出现的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个项目,我需要用另一个字符串替换所有出现的字符串。但是,如果它是文本,我只想替换该字符串。例如,我想打开这个...

 < div id =container> 
< h1> Hi< / h1>
< h2 class =Hi>测试< / h2>
Hi
< / div>

放入...

 < div id =container> 
< h1> Hello< / h1>
< h2 class =Hi>测试< / h2>
Hello
< / div>

在这个例子中,所有的Hi都变成了Hello,除了嗨作为H2类。
我尝试过...

$ $ $ $ $#容器$。$(#容器 ).html()。replace(/ Hi / g,Hello))

...但是它代替了html中所有出现的Hi以及

解决方案



pre $(#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))
})

产生此:

 < div id =container> 
< h1> Hello< / h1>
< h2 class =Hi>测试< / h2>
Hello
< / div>

jsFiddle示例

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>

jsFiddle example

这篇关于jQuery替换html页面中所有出现的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆