突出显示符合特定标准的词 [英] Highlighting Words That Fit a Specific Criteria
问题描述
我在下面有一些简单的代码,但我看不到结果.
本质上,我在一个带有 class="container"
的 div 中有一些静态文本我试图将一个函数应用于这个 div 以突出显示任何以指定字母开头的单词,在在这种情况下,起始字母 = t".然后将新文本(带高亮)返回到原始 div.
我在这里做错了什么?
//高亮任何以t开头的单词功能荧光笔(文本){text = text.split()for (var i = 0; i < text.length; i++) {如果(文本[i][0] == 't'){text[i] = ""+ text[i] + "</mark>";}}返回文本}
<div class="container" onclick=highlighter( "这是一个简单的测试,看看函数将如何执行.")>这是一个简单的测试,用于查看函数将如何执行.
在您的示例中,您计算输出,但实际上并未设置它:
<身体><div class="container";onclick="highlighter(this)">这是一个简单的测试,用于查看函数将如何执行.
<脚本>//突出显示任何以t开头的单词功能荧光笔(ev){var content = ev.innerHTML;var tokens = content.split(" ");for (var i = 0; i < tokens.length; i++) {如果(令牌[i][0] == 't'){token[i] = "<mark style='background-color:red;颜色:白色;'>>+ 令牌[i] +";}}ev.innerHTML = tokens.join("");}</html>
I have some simple code below but I am failing to see the results.
Essentially, I have some static text in a div with class="container"
I'm trying to apply a function to this div to highlight any word that begins with a specified letter, in this case the start letter = "t". Then return the new text (with highlights) to the original div.
What am I doing wrong here?
//highlight ANY word that starts with t
function highlighter(text) {
text = text.split()
for (var i = 0; i < text.length; i++) {
if (text[i][0] == 't') {
text[i] = "<mark style='background-color:red; color:white;'>" + text[i] + "</mark>";
}
}
return text
}
<div class="container" onclick=highlighter( "This is a simple test to see how the function will perform.")>
This is a simple test to see how the function will perform.
</div>
In your example you compute the output, but don't actually set it:
<!DOCTYPE html>
<html>
<body>
<div class="container" onclick="highlighter(this)">
This is a simple test to see how the function will perform.
</div>
<script>
//highlight ANY word that starts with t
function highlighter(ev) {
var content = ev.innerHTML;
var tokens = content.split(" ");
for (var i = 0; i < tokens.length; i++) {
if (tokens[i][0] == 't') {
tokens[i] = "<mark style='background-color:red; color:white;'>" + tokens[i] + "</mark>";
}
}
ev.innerHTML = tokens.join(" ");
}
</script>
</body>
</html>
这篇关于突出显示符合特定标准的词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!