javascript - 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);
}
解决方案
你的问题是:
var num = "(" + v + ")";
通过这样做,您正在检查水果(apple)
或(banana)
是否(orange)
在您的桌子上。相反,您可以删除它以检查apple
或banana
是否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>
推荐阅读
- windows - 为什么我在 Immunity Debugger 中看不到我的 shellcode 执行?
- autodesk-forge - Forge:访问集中的未发布的 Revit 模型
- spring - 如何在 Spring Security Oauth2 中使用非密码授权类型?
- javascript - 猫鼬 - 当所有字段都等于新条目时避免重复
- r - 在 R Studio 中运行时,RTools 版本 3.5 与 R 3.5 不兼容 - 有人遇到过这个问题吗?
- java - 如何让 MatchAllFilter 正常工作并将其他过滤器添加到 MatchAllfilter?
- tensorflow - 部署到 IBM Cloud 的问题
- delphi - 什么是 Delphi 的第一个版本,它允许像 double(10) 这样的类型转换
- javascript - 缓存不更新
- python - 将数字组合在一起形成多位数字