我在网站上的某个地方有一个特定的文本,假设是"lollypops",我想用“marshMellows.”替换所有出现这个字符串的地方。问题是我不知道文本的确切位置。我知道我可以这样做:
$(body).html($(body).html().replace('lollypops', 'marshmellows'));
这可能会起作用,但我需要重写尽可能少的HTML,所以我的想法如下:
即使在attributes中,也要搜索字符串
src
中替换它
例如,我会有这样的结构
<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>
。
有人知道怎么做吗?
发布于 2011-02-25 16:50:50
你可以这样做:
$("span, p").each(function() {
var text = $(this).text();
text = text.replace("lollypops", "marshmellows");
$(this).text(text);
});
最好用需要用合适的类名检查的文本来标记所有标记。
此外,这可能存在性能问题。一般来说,jQuery或javascript并不真正适合这种操作。你最好在服务器端这样做。
发布于 2011-02-25 17:20:29
你可以这样做:
$(document.body).find('*').each(function() {
if($(this).hasClass('lollypops')){ //class replacing..many ways to do this :)
$(this).removeClass('lollypops');
$(this).addClass('marshmellows');
}
var tmp = $(this).children().remove(); //removing and saving children to a tmp obj
var text = $(this).text(); //getting just current node text
text = text.replace(/lollypops/g, "marshmellows"); //replacing every lollypops occurence with marshmellows
$(this).text(text); //setting text
$(this).append(tmp); //re-append 'foundlings'
});
发布于 2013-10-14 19:05:57
下面是我用彩色文本替换一些文本的代码。它很简单,只需获取文本并将其替换为HTML
标记。它对类标签中的每个单词都有效。
$('.hightlight').each(function(){
//highlight_words('going', this);
var high = 'going';
high = high.replace(/\W/g, '');
var str = high.split(" ");
var text = $(this).text();
text = text.replace(str, "<span style='color: blue'>"+str+"</span>");
$(this).html(text);
});
https://stackoverflow.com/questions/5115152
复制相似问题