在文本中查找单词并更改颜色 [英] Find a word in text and change the color
问题描述
您好
我有一些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>"
。
推荐答案
使用createTextNode
创建一个 text 节点,没有HTML元素。
看起来你想要用包含彩色单词的新HTML替换元素的旧HTML。我无法看到你如何从JavaScript访问元素,但你可以做的基本上是这样的:
You usecreateTextNode
which creates just a text node, no HTML element.
It looks like you want to replace the old HTML of an element with the new HTML containing the colored words. I cannot see how you access the elements from your JavaScript, but what you can do is basically this:
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>
.
检查一下并适应:
Check this out and adapt:
<!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>
这篇关于在文本中查找单词并更改颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!