选择并突出显示一个单词 [英] Select and highlight a single word
本文介绍了选择并突出显示一个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试选择一个单词,然后对其应用某些内容.示例如下.
I'm trying to select a single word, then apply something to it. Example as below.
<p>Some text here</p>
是否可以选择单词文本,然后对其应用某些内容?例如 .css()-我知道您可以选择整个文本,然后选择2号单词,但这不是我想要的.这个词可能在很多地方.
Is there a way to select the word text, then apply something to it? For example .css() - I know you can select the whole text, then select word number 2, but that's not what I'm trying to do. The word could be many places.
推荐答案
查找<p>
和子级,过滤其contents
并搜索文本节点类型:
Find <p>
and children, filter their contents
and search for a textual nodeType:
var word = 'text';
var rgx = new RegExp('\\b('+word+')\\b', 'ig');
$('p, p *').contents().filter(function() {
return this.nodeType === 3;
}).each(function() {
$(this).replaceWith($(this).text().replace(rgx, '<span class="extra">$1</span>'));
});
.extra{
background:gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Some text and a link <a href="text.html">text.html</a> here and <b>some bold text there</b>. Text Is Uppercase.<br>Text... text.<br> Textual.</p>
我相信以上内容应该很有希望,因为它不会与属性字符串不匹配,因此不会使HTML崩溃.
I believe the above should be quite promising since it'll not crash the HTML since it doesn't matches attributes strings.
这篇关于选择并突出显示一个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文