JQuery查找并更改字符串的样式 [英] JQuery Find and change style of a string
本文介绍了JQuery查找并更改字符串的样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要编写一个函数来搜索HTML页面中的所有内容以查找特定的字符串,如果找到它,则更改文本的颜色。
<这可能吗?
谢谢
解决方案
你能做什么那:
CSS:
.someclass {
红色;
}
Javascript:
$('p:contains('+ yourstring +')',document.body).each(function(){
$(this).html($(this) .html()。replace(
new RegExp(yourstring,'g'),'< span class = someclass>'+ yourstring +'< / span>'
));
});
请注意,如果yourstring位于标记或属性中,则会出现问题。
在将处理程序附加到段落(或其中可能包含yourstring的元素,例如链接)之前,请小心运行此代码。
I need to write a function that will search all the content in my HTML page for a specific string, and if it finds it then change the color of the text.
Is this possible?
Thanks
解决方案
You could do that :
CSS :
.someclass {
color: red;
}
Javascript :
$('p:contains('+yourstring+')', document.body).each(function(){
$(this).html($(this).html().replace(
new RegExp(yourstring, 'g'), '<span class=someclass>'+yourstring+'</span>'
));
});
Note that this would make problems if yourstring is in a tag or an attribute.
Be careful to run this code before you attach handlers to your paragraphs (or the elements inside which could contain yourstring, for example links).
这篇关于JQuery查找并更改字符串的样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文