jQuery查找并替换字符串 [英] jQuery find and replace string
问题描述
我在网站上有一个特定的文本,让我们说lollypops,我想用marshmellows替换所有出现的这个字符串。问题是我不知道文本的确切位置。我知道我可以这样做:
I have somewhere on website a specific text, let's say "lollypops", and I want to replace all the occurrences of this string with "marshmellows". The problem is that I don't know where exactly the text is. I know I could do something like:
$(body).html($(body).html().replace('lollypops', 'marshmellows'));
这可能有用,但我需要尽可能少地重写HTML,所以我是想法:
This would probably work, but I need to rewrite as little HTML as I can, so I'm thinking something like:
- 搜索字符串
- 找到最接近的父元素
- 仅重写最接近的父元素
- 甚至在属性中替换它,但不是全部,例如在
class $ c中替换它$ c>,但不是
src
- search for the string
- find the closest parent element
- rewrite only the closest parent element
- replace this even in attributes, but not all, for example replace it in
class
, but not insrc
例如,我会有像这样的结构
In example, I would have structure like this
<body>
<div>
<div>
<p>
<h1>
<a>lollypops</a>
</h1>
</p>
<span>lollypops</span>
</div>
</div>
<p>
<span class="lollypops">Hello, World!</span>
<img src="/lollypops.jpg" alt="Cool image" />
</p>
<body>
在这个例子中,每次出现的lollypops都会被替换,只有 < img src =...
将保持不变,实际操作的唯一元素将是< a>
< span>
s。
有人知道怎么做吗?
In this example, every occurrence of "lollypops" would be replaced, only <img src="...
would remain the same and the only elements that would actually be manipulated would be <a>
and both <span>
s.
Does anybody know how to do this?
推荐答案
你可以这样做:
$("span, p").each(function() {
var text = $(this).text();
text = text.replace("lollypops", "marshmellows");
$(this).text(text);
});
标记所有标签会更好需要使用合适的类名检查的文本。
It will be better to mark all tags with text that needs to be examined with a suitable class name.
此外,这可能存在性能问题。一般来说,jQuery或javascript并不适合这种操作你最好做服务器端。
Also, this may have performance issues. jQuery or javascript in general aren't really suitable for this kind of operations. You are better off doing it server side.
这篇关于jQuery查找并替换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!