function TipsQuery(val){
a = ['a1', 'a23456', 'a1dvsgsdf', 'u9u934t'];
ret = [];
a.forEach((ele,index,self)=>{
if (ele.substring(0, inp.length) === val) {
ret.push(ele);
}
})
if(ret.length == 0){
//如果数组为空就采用关键字查询,采用分词
document.write("NO");
}
}
inp = "93";
a = ['a1', 'a23456', 'a1dvsgsdf', 'u9u934t'];
ret = [];
a.forEach((ele,index,self)=>{
if (ele.substring(0, inp.length) === inp) {
ret.push(ele);
}
})
if(ret.length == 0){
//如果数组为空就采用关键字查询,采用分词
a.forEach((ele,index,self)=>{
if (ele.search(inp) != -1) {
ret.push(ele);
}
})
}
document.write(ret);
<html>
<head>
<title></title>
<style>
.showBox {
width: 400px;
min-height: 100px;
padding: 10px;
border: 1px solid #000;
}
.text {
background: orange;
}
</style>
</head>
<div class="showBox">唧唧复唧唧</div>
<div class="showBox">木兰当户织</div>
<div class="showBox">不闻机杼声</div>
<div class="showBox">唯闻女叹息</div>
<div class="showBox">问女何所思</div>
<div class="showBox">问女何所忆</div>
<div class="showBox">女亦无所思</div>
<div class="showBox">女亦无所忆</div>
<div class="showBox">昨夜见军帖</div>
<p>
<input placeholder="请输入关键字" class="inputEl"/>
<button onclick="sendMsg()">查找</button>
</p>
<script>
var originalText = document.getElementsByClassName('showBox')[0].innerText;
function sendMsg() {
var text = originalText;
var history = document.getElementsByClassName('text');
if (history.length > 0) {
text = originalText;
}
var inputValue = document.getElementsByClassName('inputEl')[0].value;
var found = findAll(text, inputValue);
for (var i = 0; i < text.length; i++) {
for (var j in found) {
if (i == found[j]) {
text = originalText.split(inputValue).join(`<span class="text">${inputValue}</span>`);
}
}
}
document.getElementsByClassName('showBox')[0].innerHTML = text;
document.getElementsByClassName('inputEl')[0].value = "";
}
function findAll(str, x) {
var results = [];
var len = str.length;
var pos = 0;
while (pos < len) {
pos = str.indexOf(x, pos);
if (pos === -1)
break;
results.push(pos);
pos = pos + 1;
}
return results;
}
</script>
</html>
var hightTxt = document.getElementsByClassName('showBox')[2].innerHTML
document.getElementsByClassName('showBox')[2].innerHTML = "<span class='text'>" + hightTxt + "</span>"
function hightLightTxt(serchStr){
serchStr = "kevin"
a = "hiuoabnkdsgbafogkevinsssssbob";
position = a.search("kevin")
console.info(a.substring(position, position + serchStr.length))
}ele
小demo
function hightLightTxt(serchStr){
var list = Array.from(document.getElementsByClassName('showBox'));
list.forEach((ele,index,self)=>{
if(ele.innerHTML.search(serchStr) != -1){
document.getElementsByClassName('showBox')[index].innerHTML = ele.innerHTML.replace(serchStr, "<span class='text'>" + serchStr + "</span>")
}
})
}
#测试 hightLightTxt("亦无")