0

有没有人有创建自己的具有全键盘支持的 AJAX 自动建议文本框的经验?

我已经通过插入 SQL DB 并显示结果成功地创建了自动建议方面,但与搜索结果交互的唯一方法是使用鼠标。我希望能够使用键盘向上/向下滚动并使用回车键选择项目并重定向到相关页面。

我看过无数文章和帮助论坛页面,详细介绍了如何使用向上/向下箭头滚动浏览 HTML 元素,但没有解释如何将回车键合并到选择项目和重定向到相关页面。

我知道我可以使用的所有自动建议插件,但是我已经创建了自己的插件,我希望能够为结果添加额外的内容,而不是固定在其他人的工作中。

如果有人能帮我指出正确的方向,我将不胜感激。

干杯

4

1 回答 1

0

这个答案肯定属于“指向正确方向”的类别,因为我不知道您是否已经有代码以及它是什么样的(如果存在的话)。

你说你已经创建了一个带有建议的下拉菜单,所以我将省略 CSS 和 JS 来设置样式和定位。
假设下拉列表包含以下标记:

<div id="suggestiondropdown">
    <span class="suggestion" data-page="[URL of page]">Suggestion 1</span>
    <span class="suggestion" data-page="[URL of page]">Suggestion 2</span>
    <span class="suggestion" data-page="[URL of page]">Suggestion 3</span>
    <span class="suggestion" data-page="[URL of page]">Suggestion 4</span>
    <span class="suggestion" data-page="[URL of page]">Suggestion 5</span>
</div>

使用此 JS,您应该能够使用箭头键在建议之间移动:

var suggestions = document.querySelectorAll(".suggestion"); // Now suggestions is an array with the spans
var index = 0;
document.onkeypress = function(e) {
    // Style the selected as normal here:
    suggestions[index].style.backgroundColor = "#FFFFFF";
    if (e.keyCode == 38) { // UP!
        if (index <= 0) index = suggestions.length;
        index--;
    }
    else if (e.keyCode == 40) { // DOWN!
        if (index >= suggestions.length -1) index = -1;
        index++;
    }
    else if (e.keyCode == 13) { // ENTER!
         var page = suggestions[index].dataset.page;
         window.location.href = page; // Or with relative URLs, first prepend the base URL.
    }
    // Style the selected one as selected here.
    // I don't know how you want it, so I'll just give the selected one a blue background.
    suggestions[index].style.backgroundColor = "#0000FF"; // Never mind the ugly shade

}

未经测试

于 2013-01-30T16:22:04.470 回答