Using js to realize the effect of simple term matching display in the input box
- The necessary explanations are all in the code comments, which are easy to understand when used for reference by partners.
<body>
<div id="box">
<input type="text" name="" id="txt">
<input type="button" name="" id="" value="search">
</div>
</body>
<script>
var keyWords = ["it's a nice day today", "It's raining today", "Typhoon is very big.", "Shanghai","Today is a good day"];
document.getElementById("txt").onkeyup = function () {
// Every time the keyboard is raised, you should judge whether there is dv or not
if (document.getElementById("dv")) {
document.getElementById("box").removeChild(document.getElementById("dv"));
}
// Used to store matching hot words.
var tempArr = [];
// The text obtained in the text box, i.e. value
var txt = this.value;
for (var i = 0; i < keyWords.length; i++) {
//Each item of the array must be compared with the input
if (keyWords[i].indexOf(txt) == 0) {
tempArr.push(keyWords[i]);
}
}
// dv is removed if the input box has no words and the length of the temporary array is 0
if (this.value.length == 0 || tempArr.length == 0) {
if (document.getElementById("dv")) {
document.getElementById("box").removeChild(document.getElementById("dv"));
}
return;
}
// Create a div with hot words, add it to the box, and set the corresponding style.
var dvObj = document.createElement("div");
my$("box").appendChild(dvObj);
dvObj.id = "dv";
dvObj.style.width = "200px";
dvObj.style.border = "1px solid #999";
// Put every hot word in P
for (var j = 0; j < tempArr.length; j++) {
var pObj = document.createElement("p");
dvObj.appendChild(pObj);
pObj.innerText=tempArr[i];
pObj.style.margin = "0";
pObj.style.padding = "0";
pObj.style.marginTop = "5px";
pObj.onmouseover=function(){
this.style.backgroundColor="lightgrey";
};
pObj.onmouseout=function(){
this.style.backgroundColor="";
};
}
};
</script>
The implementation of this small effect mainly uses the following knowledge points:
- The onkeyup event is the event that the keyboard is raised.
- keyWords[i].indexOf(text)==0 uses the search method in the array (arr.indexOf(elemnte) to find the position where the element first appears in the array, starting from 0, if not, the return value is - 1)
- tempArr.push(keyWords[i]) uses the stack method in the array (arr.push(element) inserts the element at the back of the array)
- document.getElementById("box").removeChild(document.getElementById("dv")) uses the knowledge point of removing the child node (parent element. Removechild (child element to be removed))
- var dvObj = document.createElement("div"); the method of creating elements (document.createElement("element to be created")) is used. Pay attention to quotation marks~
-
My $("box"). AppendChild (dvob j); method of adding child element is used (parent element. AppendChild (element J to be added))
Finally, attach the figure