在文本中查找单词并更改颜色

在文本中查找单词并更改颜色

本文介绍了在文本中查找单词并更改颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好

我有一些li标签,我想在其中找到一个特定的单词并使用JavaScript更改单词的颜色:



我的尝试:



代码一:

Hello
I have some li tags that I want to find a specific word in them and change the color of the word using JavaScript:

What I have tried:

code one:

var text = result.replace(_word, _word.fontcolor("red"));
var _test = document.createTextNode("text");



它只是替换


it just replace

"<font color='red'> _word </font>"

使用_word而不是更改颜色。



代码拖曳:

with _word instead of changing color.

code tow:

var text = result.replace(_word, "<span style='color:red'>" + _word "</span>");
var _test = document.createTextNode("text");



它只是替换


it just replace

"<span style='color:red'> _word </span>"

推荐答案

var element = ...; // if you want to get the element by ID: document.getElementById("your-element");
var originalHtml = element.innerHTML;
var newHtml = originalHtml.replace(_word, _word.fontcolor("red"));
element.innerHTML = newHtml;



请注意.replace仅替换单词的第一个匹配项。如果要替换所有实例,可以使用正则表达式:


Note that .replace only replaces the first occurrence of the word. If you want to replace all occurrences, you can use a regular expression:

var newHtml = originalHtml.replace(new RegExp(_word, "g"), _word.fontcolor("red")); // "g" means "global"



另请注意,设置 innerHTML 属性会导致元素丢失所有事件处理程序。因此,如果您的事件处理程序绑定到li元素,那么我建议不要将文本立即放在li-tag中,而是放在li标记中的另一个标记中,如下所示:< li>< span>你的文字< / span>< / li>


Also note that setting the innerHTML property causes the element to lose all event handlers. So if you have event handlers bound to your "li"-elements, then I recommend to not put your text immediately in the li-tag, but in another tag in the li tag, like this: <li><span>your text here</span></li>.


<!DOCTYPE html>
<html>
<body>

<p id="demo">Visit CodeProject!</p>

<button onclick="changeSubStringColor()">Try it</button>

<script>
function changeSubStringColor() {
    var str = document.getElementById("demo").innerHTML;
    var res = str.replace("CodeProject", "<span style='color:red'>CodeProject</span>");
    document.getElementById("demo").innerHTML = res;
}
</script>

</body>
</html>


这篇关于在文本中查找单词并更改颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 22:38