突出显示符合特定标准的词 [英] Highlighting Words That Fit a Specific Criteria

查看:38
本文介绍了突出显示符合特定标准的词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面有一些简单的代码,但我看不到结果.

本质上,我在一个带有 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屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆