【问题标题】:Keyboard navigation (up & down arrow) for Ajax drop downAjax 下拉菜单的键盘导航(向上和向下箭头)
【发布时间】:2012-10-06 05:05:00
【问题描述】:

我按照 W3Schools 教程进行了 AJAX 实时搜索,它运行良好。我将 AJAX 结果作为锚元素返回。

我想为 Ajax 下拉菜单添加键盘导航(即向上箭头和向下箭头),我最好的结果是将焦点放在仅停留一秒钟的第一个结果上,然后焦点消失。我想知道为什么这个焦点会消失,以及任何绕过它的方法。

我的 JavaScript 代码:

<script type="text/javascript">
    $(document).ready(function(){
        $('#searchInput').keyup(function(e){
            var keyCode = e.keyCode || e.which;
            if (keyCode == 40){
                 $('.hint').first().focus();
                 $('.hint').first().css('color','#E8AE00'); //I can get the focus to here, but the focus will disappear right away.
            }
        })
    })
</script>

这是我的 PHP 代码:

<?php
    $q = $_GET["q"];
    $xmlDoc = new DOMDocument();
    $xmlDoc -> load("database.xml");
    $rest = $xmlDoc -> getElementsByTagName('restaurant');

    if (strlen($q)>0){
        $hint[] = "";
        $index = 0;
        for ($i = 0; $i < ($rest->length); $i++){
            $name = $rest -> item($i) -> getElementsByTagName('name');
            $link = $rest -> item($i) -> getElementsByTagName('link');
            if ($name -> item(0) -> nodeType == 1){
                if (strtolower($q) == strtolower(substr($name -> item(0) -> childNodes -> item(0) -> nodeValue,0,strlen($q)))){ //if matching
                    $hint[$index] = "<a class='hint' id='hint".$index."' href='".$link -> item(0) -> childNodes -> item(0) -> nodeValue."' onfocus=\"this.style.color='#E8AE00'\">".substr($name -> item(0) -> childNodes -> item(0) -> nodeValue,0,strlen($q))."<b>".substr($name -> item(0) -> childNodes -> item(0) -> nodeValue,strlen($q))."</b></a><br />";
                    $index++;
                }
            }
        }
    }

    if ($hint[0] == ""){
        echo "no suggestion";
    }
    else {
        for ($j = 0; $j < (count($hint)); $j++){
            echo $hint[$j];
        }
    }
?>

谢谢。

【问题讨论】:

  • keyup 之后还有其他方法运行吗?听起来好像另一个事件侦听器或延迟方法正在吸引您的注意力。

标签: javascript jquery ajax keyboard-navigation


【解决方案1】:

可能下拉菜单正在消失,因为您正在调用 $('.hint').first().focus();,这会从(又名模糊)#searchInput 窃取焦点。我认为模糊输入会隐藏下拉列表,因为您没有在此处包含一些 JS 代码,这些代码(正确地)隐藏了下拉列表。

我不确定你为什么需要在提示时致电focus()

【讨论】:

    【解决方案2】:

    您正在构建具有焦点内联 javascript 事件的链接,这似乎真的没有必要?

    <a class='hint' id='hint" ...... onfocus=\"this.style.color='#E8AE00'\">"
    

    另外,请注意您多次生成相同的 ID?它们应该是独一无二的!

    如果您使用一些 jQuery 并创建一个委托鼠标事件,然后触发该事件而不是焦点事件,它应该很可能工作?

    $(function(){
        $(document).on({
            mouseenter: function() {
                $(this).css('color', '#E8AE00')
            }
        }, '.hint');
    
        $('#searchInput').on('keyup', function(e){
                if (e.which == 40){
                     $('.hint').first().trigger('mouseenter');
                }
        });
    });
    

    【讨论】:

    • 重复是我的错误。我一直在玩代码,一定忘记了。关于 ID,我实际上为它分配了一个数字变量:hint0、hint1、hint2、...。虽然“聚焦”对结果没有太大影响。
    • 嗨,Adeneo,我试过你的。它仍然没有解决焦点问题。焦点不断回到#searchInput。当我添加额外的行来模糊#searchInput 时,焦点转到滚动条。