首页 > 解决方案 > JS Chrome 插件 - 查找位于当前活动选项卡中的文本

问题描述

下面的代码基于此示例中提供的示例: StackOverflow Question

我不擅长 JS,但想调整此代码以不仅突出显示位于网站上的 a 中的数字,而且通过更改字体颜色或突出显示文本来突出显示位于活动选项卡中任何位置的特定文本。我怎样才能做到这一点?

感谢任何帮助,我是 JS 新手,有点迷茫。谢谢, A2K

编辑:为了澄清,我想突出显示 Apple、Banana 等词,当它们位于活动选项卡中的任何位置时,不一定在表或 td 中。这意味着单词也可以出现在一段文本中、标签中、输入字段等中。

highlightText.js

// keyword to highlight
var keywordArray = ["apple","banana","orange"];

keywordArray.forEach(function(v){
  var num = "(" + v + ")";

  // Select the '<td>' that contains the number we are looking for
  var td = $('td.col-question:contains('+num+')');

  // Make sure that this number exists
  if(td.length > 0){

    // Now that we have it we need to single out the number and replace it
    var span = td.html().replace(num,'<span class="highlight-num">'+num+'</span>');
    var n = td.html(span);
  }
    // Now instead of '(1000)' we have
    // '<span class="highlight-num">(1000)</span>'
    // We will color it in the css file
});

高亮.css

span.highlight-num{
  background-color: rgb(100, 255, 71);
}

标签: javascriptgoogle-chrome-extension

解决方案


你的问题是:

var num = "(" + v + ")";

通过这样做,您正在检查水果(apple)(banana)是否(orange)在您的桌子上。相反,您可以删除它以检查applebanana是否orange包含在您的表中。

如果关键字出现在它们周围以突出显示它们,您可以改为使用正则表达式替换关键字。

然而,这确实有它的缺点,因为它不能与文本输入一起正常工作,因为标记不会呈现为 HTML。

请参阅下面的工作示例:

$(function() {
  const keywordArray = ["apple", "banana", "orange"];
  const body = $('body');

  body.html((_, innerHTML) =>
    innerHTML.replace(new RegExp(`(${keywordArray.join('|')})`, 'g'), '<span class="highlight-num">$1</span>')
  );
});
span.highlight-num {
  background-color: rgb(100, 255, 71);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
  <p>The big apple is big</p>
  <em>The orange <strong>orange</strong> is orange</em>
  <br />
  <span>The green grape is green</span>
  <h4>The banana is a banana</h4>
</body>


推荐阅读