为AJAX Live Search PHP添加快捷键(键盘箭头向上/向下)支持

Add keydown (keyboard arrow up/down) support for AJAX Live Search PHP

本文关键字:向下 支持 键盘 Search Live AJAX PHP 添加 快捷键      更新时间:2023-09-26

提前感谢您的关注,

我正在使用W3 PHP AJAX Live搜索示例,它已经集成在这个网站上。简直太完美了。我希望使用键盘上的箭头,向上(或向左)和向下(或向右),以聚焦<div id="livesearch">内部的结果。然后,在对焦时按Enter -div键加载。

在HTML中:

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <style>
    #livesearch {
        min-height: 155px;
    }
    #livesearch a:hover {
        text-decoration: none;
        background-color: rgba(0,0,0,0.05);
    }
    #livesearch a {
        text-transform: capitalize;
        font-size: inherit;
        padding: 5px 13px;
        display: block;
    }
    #livesearch .selected {
        text-decoration: none;
        background-color: rgba(0,0,0,0.05);
    }
    </style>
</head>

HTML表单:

<body>
    <form method="post" id="myfrm">
        <input type="text" name="search" class="form-control search" placeholder="Just start typing..." autofocus="">
    </form>
    <div id="livesearch"><div>
</body>
AJAX函数:
<script>
    function showResult(str) {
      if (str.length==0) { 
        document.getElementById("livesearch").innerHTML="";
        document.getElementById("livesearch").style.border="0px";
        return;
      }
      if (window.XMLHttpRequest) {
        xmlhttp=new XMLHttpRequest();
      } else { 
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
      xmlhttp.onreadystatechange=function() {
        if (this.readyState==4 && this.status==200) {
          document.getElementById("livesearch").innerHTML=this.responseText;
        }
      }
      xmlhttp.open("GET","livesearch.php?q="+str,true);
      xmlhttp.send();
    }
</script>
Jquery:

<script>
$(document).ready(function ($) {
    $('.search').keyup(function (e) {
        var key = e.keyCode;
        if (key == 40 || key == 38 || key == 13) {
           return false;
        }
        var str = $('.search').val();
        showResult(str);
    });
    $('#myfrm').on("keydown", ".search", function (e) {
        var $listItems = $('#livesearch a');
        var key = e.keyCode,
                $selected = $listItems.filter('.selected'),
                $current;
        if (key != 40 && key != 38 && key != 13)
            return;
        //$listItems.removeClass('selected');
        if (key == 40) // Down key
        {
            $listItems.removeClass('selected');
            if (!$selected.length || $selected.is(':last-child')) {
                $current = $listItems.eq(0);
            } else {
                $current = $selected.next();
            }
            console.log("Current : "+$current);
        } 
        else if (key == 38) // Up key
        {
            $listItems.removeClass('selected');
            if (!$selected.length || $selected.is(':first-child')) {
                $current = $listItems.last();
            } else {
                $current = $selected.prev();
            }
        } 
        else if (key == 13) // Enter key
        {
            $current = $listItems.filter('.selected');
            $current.trigger('click');
            return false;
        }
        $current.addClass('selected');
    });
});
</script>

livesearch数据中检索input搜索框中的数据:

<script>
$(document).ready(function ($) {
    $("body").on("click", "#livesearch a", function(e){
        e.preventDefault();
        var data = $(this).text();
        $(".search").val(data);
        $('#livesearch').html('');
    });
});
</script>

如果你想用ajax代替showResult(str)使用ajax+jquery的数据检索livesearch.php所以,你可以使用下面的代码:

<script>
$(document).ready(function ($) {
    $('.search').keyup(function (e) {
        var key = e.keyCode;
        if (key == 40 || key == 38 || key == 13) {
          return false;
        }
        var str = $('.search').val();
        $.ajax({
            context: this,
            url: 'livesearch.php',
            type: 'get',
            dataType: 'html',
            data: {
                q: str,
            },
            beforeSend: function () {
                console.log("Loadding...");
            }
        }).done(function (response) {
            $("#livesearch").html(response);
        });
    });
});
</script>
document.getElementById("yourtextfield").addEventListener("keyup",function(event){
    var livesearchelem = document.getElementById("livesearch");
    var childrens = livesearchelem.getElementsByTagName("a"); //Get only hyperlinks
    var key = event.keyCode;
    var selected = this.selectedResultNumber;
    if (key == 38){ //Arrow up
        if (childrens.length === 0){ return; }
        if (!selected){ //If 'selectedResultNumber' is undefined
            childrens[childrens.length - 1].style.backgroundColor = 'blue';
            childrens[childrens.length - 1].style.color = 'white';
            //Store the selected number into this element
            this.selectedResultNumber = childrens.length - 1;
        }
        else if (selected > 1){
            //Restore the previous selected element's style
            childrens[selected - 1].style.backgroundColor = 'white';
            childrens[selected - 1].style.color = 'black';
            //Set the new selected element's style
            childrens[selected - 2].style.backgroundColor = 'blue';
            childrens[selected - 2].style.color = 'white';
            //Decrease the selected number by 1
            this.selectedResultNumber--;
        }
    }
    else if (key == 40){ //Arrow down
        if (childrens.length === 0){ return; }
        if (!selected){ //If 'selectedResultNumber' is undefined
            childrens[0].style.backgroundColor = 'blue';
            childrens[0].style.color = 'white';
            //Store the selected number into this element
            this.selectedResultNumber = 1;
        }
        else if (selected < childrens.length){
            //Restore the previous selected element's style
            childrens[selected - 1].style.backgroundColor = 'white';
            childrens[selected - 1].style.color = 'black';
            //Set the new selected element's style
            childrens[selected].style.backgroundColor = 'blue';
            childrens[selected].style.color = 'white';
            //Increase the selected number by 1
            this.selectedResultNumber++;
        }
    }
    else if (key == 13){ //Enter key
        if (childrens.length === 0){ return; }
        //Trigger click event on the selected element
        childrens[selected - 1].click();
    }
    else{ //Searching in progress
        delete this.selectedResultNumber;
        //Your search function goes here
    }
});