问题描述
我尝试查找和替换文本(使用jQuery).实际上,我正在尝试在文本周围添加一个span元素.我还应该能够再次删除跨度,而不会丢失其中的文本.
I try to find and replace text (using jQuery). Actually I'm trying to add a span element around the text. I should also be able to remove the span again without losing the text inside.
例如,假设我从以下情况开始:
For example, let's say I have the following situation to start with:
<span>This is a span element</span>
我希望能够使用jQuery/JavaScript动态地做到这一点:
And I want to be able to do this dynamically using jQuery/JavaScript:
<span>This is a <span class="marked">span</span> element</span>
我还应该能够删除已标记的span并返回到第一个结果.
I should also be able to remove the span.marked and get back to the first result.
但是问题是我想对具有多个子级和子级等等的容器中的所有文本执行此操作.
The problem however is that I want to do this on all text inside a container with multiple children and subchildren and so on.
到目前为止,我得到的代码将执行以下操作,而这并不是我想要的:
The code I got so far will do the following and that is not what I want:
<<span class="marked">span</span>>This is a <span class="marked">span</<span class="marked">span</span> element</span>
我想对页面上的所有文本执行此操作,而不仅仅是找到的第一个文本.
I want to do this for ALL text on the page, not just the first it finds.
到目前为止,我的代码是这样做的
my code so far for doing this:
var re = new RegExp(word, 'g');
$('.container').html($('.container').html().replace(re, '<span class="marked">' + word + '</span>'));
word是一个字符串,其中包含要环绕的文字.
word is a string with the text to wrap spans around.
推荐答案
要在html中包装搜索字符串,您可以使用类似以下的内容:
To wrap a search string in html you can use something like this:
$('span:contains("word")').html().replace('word', '<span class="marked">word</span>');
并删除它,您可以使用以下内容:
and to remove it, you can use something like this:
$('span:contains("word")').html().replace('<span class="marked">word</span>', 'word');
是的,这是一种很粗糙的方法,但是应该可以.
Yes this is a pretty crude way of doing it but it should work.
正如@ user3558931指出的那样,该单词必须是一个变量.
as pointed out by @user3558931, the word needs to be a variable.
要将搜索字符串包装为html,您可以使用类似以下内容的内容:
To wrap a search string in html you can use something like this:
$('span:contains("' + str + '")').html().replace(str, '<span class="marked">' + str + '</span>');
并删除它,您可以使用以下内容:
and to remove it, you can use something like this:
$('span:contains("' + str + '")').html().replace('<span class="marked">' + str + '</span>', str);
上面的代码有故障,请参见此提琴中的固定代码: http://jsfiddle.net/thePav/7TNk6/21/
A glitch in the above code, see the fixed code in this fiddle: http://jsfiddle.net/thePav/7TNk6/21/
这篇关于jQuery:查找文本并替换为HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!