【问题标题】:Add keydown (keyboard arrow up/down) support for AJAX Live Search PHP为 AJAX Live Search PHP 添加 keydown(键盘向上/向下箭头)支持
【发布时间】:2017-03-17 19:01:22
【问题描述】:

提前感谢您的关注,

我正在使用W3 PHP AJAX Live Search Example,它已经集成了on this site。这几乎是完美的。我希望使用键盘上的箭头,向上(或向左)和向下(或向右),将结果集中在<div id="livesearch"> 内。然后,在焦点上按 Enter ⏎ 键加载。

【问题讨论】:

  • 也可以从拥有它的一个开始,而不是添加到现有的:jqueryui.com/autocomplete。是的,这是一个糟糕的问题(没有代码,没有研究,没有尝试自己回答)我们不只是在这里为您正确编码。
  • 搜索了15分钟后,好像网上所有的demo和教程都有“加载缓慢”的实时搜索结果。感谢您的反馈和祝你好运@nogad 或 /u/nogad - 我会听取你的建议并继续前进...我也可以从这篇文章中了解更多信息stackoverflow.com/a/819780/1927168

标签: javascript autocomplete


【解决方案1】:

在 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+jquery 代替 ajax showResult(str) 来检索数据 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>

【讨论】:

  • 非常好的反馈,感谢您的意见。我添加了编码,仍然在玩弄东西,它不起作用但你可以看到触发器被触发,并且 css 工作......如果你愿意,再次访问页面 - von.host/knowledgebase.php
  • 嗨,我重新访问了您的网站,我发现了一些问题,我已根据上一个问题更新了我的答案。在 2 个函数 $('.search').keyup(function (e) {$("body").on("click", "#livesearch a", function(e){ 中编辑了我的答案
  • 第一个函数添加var key = e.keyCode; if (key == 40 || key == 38 || key == 13) { return false; } 和第二个函数添加$('#livesearch').html(''); 请仔细关注并粘贴我的代码。我现在已经 100% 工作了。
【解决方案2】:
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
    }
});

【讨论】:

  • 感谢 cmets,非常有帮助。您上面的代码是否被包裹在&lt;script&gt; 中,而不是放在 livesearch.php 文件中?或者,我将代码添加到标题中?我现在还在玩弄东西,我会尽快回复更新。
  • 是的,您可以将其包装在 &lt;script&gt; 中,但将其放在“knowledgebase.php”中,而不是“livesearch.php”中。确保在文档加载后调用它。
猜你喜欢
  • 2010-09-21
  • 1970-01-01
  • 2012-10-06
  • 2018-09-16
  • 1970-01-01
  • 2012-05-03
  • 1970-01-01
  • 2013-05-22
  • 1970-01-01
相关资源
最近更新 更多