想做个类似于 word的查找替换功能,给查找到的词添加标签,并设置背景,加以强调,但是在使用replace时出了故障,各位能帮我解决一下bug么?-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
*{
padding: 0;
margin: 0;
}
html,body{
height: 100%;
}
#box{
width: 500px;
height: 300px;
border:1px solid #ccc;
}
#sea{
width: 300px;
height: 100px;
background: #fad;
left: 0;right: 0;bottom: 0;top: 0;margin: auto;
position:absolute;
display:none;
text-align: center;
}
i{
background: red;
}
</style>
</head>
<body>
<button id="showsearch">查找</button>
<div id="box">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Similique magni, aut. Cum quos quam ad dignissimos molestias vero nihil quo
</div>
<div id="sea">
<h3>请输入查找内容:</h3>
<input type="text" id="searchkeyword" autofocus="autofocus"><button id="isearch">查找</button>
</div>
<script>
var oBox = document.getElementById("box");
var showSearch = document.getElementById("showsearch");
var iSearch = document.getElementById("isearch");
var str = oBox.innerHTML;
var strx,stry;
//点击时 显示查询框 获取查询词
showSearch.onclick = function(){
sea.style.display= "block";
iSearch.onclick = function(){
strx = searchkeyword.value;
sea.style.display= "";
a = '<i>'+strx+'</i>';
searchs(strx,a);
}
}
//查询函数
function searchs(x,y){
for( var i = 0,l = str.length;i<l; i ++ ){
str = str.replace(x,y)
console.log(str);
console.log(str.length)
}
oBox.innerHTML = str;
}
</script>
</body>
</html>
故障的地方在这里,每一次查询都会从第一次查询到的词开始,造成了重复死循环。该怎样才能把第一次的词跳过去呢?我尝试过给查询函数添加个i;
function searchs(x,y){
for( var i = 0,l = str.length;i<l; i ++ ){
str = str.replace(x,y);
//但是仍然是死循环
i = str.charCodeAt(i) + 8;
console.log(str);
console.log(str.length)
}
oBox.innerHTML = str;
}
你怎么会觉得
i
能影响到str.replace
呢,替换的字符带原有字符的情况下最好不用replace
,楼上换正则的方式如果高亮文字里包含正则的特殊字符就不行了。可以这么做