You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让jQuery UI autocomplete获取焦点时自动展开下拉列表

jQuery UI Autocomplete 聚焦时自动展开完整下拉列表解决方案

问题分析

你当前用$(this).autocomplete("search", " ");触发搜索没效果,核心原因有两个:

  • 传递空格作为搜索关键词,若你的tagInputOptions数据源里没有包含空格的选项,过滤后无匹配结果,自然不会展开下拉框。
  • jQuery UI Autocomplete默认的minLength参数是1,只有当输入字符长度≥1时才会触发搜索,空字符串或空格(长度1但无匹配)都无法触发完整列表展示。

解决步骤

要实现聚焦时显示完整未过滤列表,需要两步调整:

  1. 初始化时设置minLength: 0
    允许空搜索触发下拉列表,这是基础前提。

  2. 聚焦时触发空搜索
    调用autocomplete("search", ""),此时因为minLength为0,会返回完整的数据源列表。

修改后的完整代码

$(".tag-input").autocomplete({
    source: tagInputOptions,
    sortResults: true,
    minLength: 0, // 新增:允许空搜索
    select: function (event, ui) {
        var selectedValue = ui.item.value;
        if (selectedValue !== "") {
            $(this).next(".tag-input-button").click();
        }
        return false;
    }
}).keydown(function(event) {
    if (event.originalEvent.keyCode === 13) {
        event.preventDefault();
        var selectedValue = $(this).val();
        if(selectedValue !== "") {
            $(this).next(".tag-input-button").click();
        }
    }
}).on("focus", function () {
    $(this).autocomplete("search", ""); // 修改为搜索空字符串
});

额外说明

如果你的tagInputOptions是一个函数(而非数组),需要确保函数能处理空搜索关键词的情况,返回完整的数据源列表。比如:

source: function(request, response) {
    if (request.term === "") {
        // 返回完整列表
        response(tagInputOptions);
    } else {
        // 原有过滤逻辑
        var filtered = $.grep(tagInputOptions, function(item) {
            return item.value.indexOf(request.term) !== -1;
        });
        response(filtered);
    }
}

内容的提问来源于stack exchange,提问作者gardarvalur

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 14:12:14