我正在做一个项目,如果我们在数组上找到给定单词,我想更改它的文本颜色。例如,我有一个数组
["Lorem","nemo"]
,我得到的文本来自 body 标签
这是我的索引文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body id="body">
<div>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Inventore sed sequi quos veniam? Cum consectetur exercitationem maxime, aperiam saepe reprehenderit fuga ipsa labore rerum ex error fugiat quasi accusantium nemo.
</div>
<div>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Inventore sed sequi quos veniam? Cum consectetur
exercitationem maxime, aperiam saepe reprehenderit fuga ipsa labore rerum ex error fugiat quasi accusantium nemo.
</div>
<div>
Here, we have used a regular expression to match a certain portion of the string. We can capture certain groups in the
match using matchAll() better than match().
</div>
<script src="main.js"></script>
</body>
</html>
这是我的 javascript
function change(){
var text = document.querySelector("body");
var string = text.innerHTML;
// let searching = ["Lorem", "nemo","amet","better","matchAll"];
let searching = ["Lorem","nemo"];
// search
for(search of searching){
var textfind = string.matchAll(search)
for(m of textfind){
// console.log(m[0])
let statring_index = m.index;
let ending_index = m[0].length;
let giventext = string.substring(statring_index, statring_index+ending_index)
console.log(giventext)
// giventext = giventext.replace("/"+m[0]+"/g","<span style='color:red';>"+ giventext + "</span>")
// document.write("<span style='color:red;>"+ m[0] + "</span>")
var redText = string.substring(statring_index, statring_index+ending_index);
text.innerHTML = string.substring(0,statring_index)+"<a style='color:red;'>"+redText+"</a>"+string.substring(statring_index+ ending_index);
}
}
}
change()
现在的问题是,我希望所有出现的事件都为红色,但我的代码只能更改数组中的最后一个元素一次
所以如果我们在搜索数组中有那个词,我想把所有出现的地方都改成红色