Home > Web Front-end > JS Tutorial > body text

js implements keyword prompts in web search box

韦小宝
Release: 2018-03-14 12:43:09
Original
5603 people have browsed it

When we browse the website, we often encounter search boxes and the like. When we enter the content we want to search, some prompts will pop up below. For such operations, we use JavaScript Since it can be achieved, let’s explain how to achieve it!

When writing this function, I am very particular about the details. If I don’t pay attention to it, various discomforts will appear on the page.
Let’s take a look at the effect first:
js implements keyword prompts in web search box
When I am Enter a character in the input box, and the corresponding content will appear later. Just click on us to link to the corresponding document area, which is very suitable for site search and navigation.
I present the complete test code below.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <form id="form" name="form">
        搜索:<input type="text"  name="input1">
    </form>
    <p id="wrap" style="width: 100;height: 100px;border: 1px solid black;"></p>
    <script type="text/javascript">
        var form = document.getElementById("form");
        var input1 = document.forms["form"]["input1"];
        var wrap = document.getElementById("wrap");

        var arr1 = [" 我爱中国"," 我爱美国"," 我爱英国"," 我天生神力"];//数组里面的元素就是我希望在输入宽输入某个字符后在下方出现的搜索字符。
        var arr2 = [];//这个数组是为了装入经过筛选和匹配符合要求的arr1中的元素。例如输入值为"我",arr1中的4个元素都出现。输入"我爱",则出现前三个。出现的元素都要装入到arr2中方便后面依据数组中的元素创建元素。

        input1.oninput = function() {//添加input监控,这样我们可以随时感知输入框值的变化
            var val = input1.value;//获取当前输入框的值。
            arr2 = [];//使得每次输入框值变化后数组arr2为空。不然每改变一次值就创建一次元素而不删除的话,wrap中添加的元素会越来越多。

            /*清掉wrap里面的所有p元素。这里要注意一个问题,很重要。我们在获取wrap内的p元素的时候要注意以下几个问题:
            1.getElementsByTagName("p");返回的是一个数组而不是一个元素,不能直接通过remove()删除;
            2.使用querySelectorAll("p")获取p元素,使用for循环删除所有p元素不能按照以下方式写:
                 for (var k = 0; k < p1.length; k++) {
                    p1[k].remove();
                };
                因为将数组内的元素从下标为0的元素开始删除,每删除一个,删除前下标为1的元素就会自动下标为0的位置。这样通过上面的循环并不能将wrap中的元素删除干净。
                你可以这样写:
                for (var k = p1.length-1; k >= 0; k--) {
                    p1[k].remove();
                };
                或者不要通过getElementsByTagName("p")这种方式获取元素,而是通过querySelectorAll("p")就不会出现上面的问题。

            */

            var p1 = wrap.getElementsByTagName("p");
            // var p1 = wrap.querySelectorAll("p");
                for (var k = p1.length-1; k >= 0; k--) {
                    p1[k].remove();
                };

            //indexOf用来查看arr1中的每个元素是否包含输入款的字符。包含则返回第一个下标,不包含则返回-1.这里要注意输入框中的值为空时返回的0,输入第一个字符为"我"也返回0,这时如果用(arr1[i].indexOf(val) > -1为条件,输入框为空时也会在wrap内生成p元素。所以我在arr1数组元素字符串第一个位置加一个空格,这样输入第一个字符为"我"返回1,再将条件变为arr1[i].indexOf(val) > 0 
            for (var i = 0; i < arr1.length; i++) {
                if (arr1[i].indexOf(val) > 0 ) {
                    // console.log(val);
                    arr2.push(arr1[i]);
                }   


            //创建元素的循环。在每个创建的元素内添加arr2数组中的字符串。

            for (var j = 0; j < arr2.length; j++) {

                var p = document.createElement("p");
                var a = document.createElement("a");
                    a.innerText = arr2[j];
                    a.setAttribute("href","http://www.baidu.com");
                    p.appendChild(a);
                    wrap.appendChild(p);

                }
            }   

    </script>
</body>
</html>
Copy after login

My coding ideas:
1. Form input box.
2. Be sure to monitor the value changes of the form input box. By adding the event oninput
3, how does the search value appear and it can be an input value Exercise together.

  • Put the search value into an array, retrieve whether the elements in the array contain the input box value through indexOf, and filter out these values. In this way, the input box value and the search box value are connected together.

  • Put the value that meets the condition into the created p element, and then put the p element into wrap.

4. At this time, you may encounter the first major problem. Constantly changing the value of the input box, there are more and more p elements in wrap, and they are repeated continuously. .
what to do?
Create an array again, put all arr1 array elements that meet the conditions into this array, and then write a judgment to determine whether the value selected each time is in array arr2. If it does not belong, add
In this way, duplicate elements will not be added to array arr2.
5. Then you will find out why the elements are still appearing repeatedly. This is an element residue problem, that is, the previous elements are not deleted. After each change you need to delete the elements that have been created in the wrap, otherwise they will still exist. This is done using getElementsByTagName() to get the elements and remove them.
6. The general function has been completed, and then there are some small details, but it is these small details that waste time.
One is that the search value will also appear when the input box has an empty value. Is arr1[i].indexOf(val) greater than 0 or -1? It turns out that the return value of a null value is also 0, which will also execute the code that creates the element, so I added a space before each string in arr1 .
The other is the key points to pay attention to when using getElementsByTagName() to get elements. It is important to know. I was stuck on this issue for a long time. The above code areas are explained in detail.

Related recommendations:

Implementation of automatic prompt function for javascript search

The above is the detailed content of js implements keyword prompts in web search box. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template