键入时不要显示jQuery UI自动完成

Do not show jQuery UI Autocomplete when typing

本文关键字:UI jQuery 显示      更新时间:2024-01-14

我正在使用jQuery UI自动完成功能来显示文本输入的自动完成。我想要更逼真的列表何时出现。我已经为Click和Double Click制作了触发器,它们显示自动完成(基于用户是否选择包含每个触发器),但我没有发现影响自动完成在键入时是否显示的方法。

如何使键入时不显示自动完成(不由关键事件触发)?

回答

function InitialiseAutoCompleteEx(inputId, trigOnClick, trigOnDoubleClick, trigOnType, trigOnCtrlSpace, rawAutoCompleteItems)
{
    var autoCompleteItems = rawAutoCompleteItems.split("|");
    var input = $("#" + inputId);
    input.autocomplete(
        {
            source: autoCompleteItems,
            minLength: 0,
            disabled: true,
            close: function() { $(this).autocomplete("option", "disabled", true); }
        });
    if (trigOnClick)
    {
        input.click(function()
            {
                $(this).autocomplete("option", "disabled", false);
                $(this).autocomplete("search");
            });
    }
    if (trigOnDoubleClick)
    {
        input.dblclick(function()
            {
                $(this).autocomplete("option", "disabled", false);
                $(this).autocomplete("search");
            });
    }
    if (trigOnType)
    {
        input.keydown(function(event)
            {
                var key = String.fromCharCode(event.which);
                if ( /[a-zA-Z0-9]/.test(key) )
                {
                    $(this).autocomplete("option", "disabled", false);
                    $(this).autocomplete("search");
                }
            });
    }
    if (trigOnCtrlSpace)
    {
        input.keydown(function(event)
            {
                if (event.which == 32 && event.ctrlKey)
                {
                    $(this).autocomplete("option", "disabled", false);
                    $(this).autocomplete("search");
                    event.preventDefault();
                }
            });
    }
}

只需使用其disabled选项:

$("#field").autocomplete("option", "disabled", true);

var tags = ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"];
$("#field").autocomplete({
  source: function(request, response) {
    var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(request.term), "i");
    response($.grep(tags, function(item) {
      return matcher.test(item);
    }));
  },
  disabled: true,
});
function disable(shouldDisable) {
  shouldDisable = JSON.parse(shouldDisable); // Extract boolean from string parameter
  $("#field").autocomplete("option", "disabled", shouldDisable);
  $("#field").focus().trigger($.Event("keydown"));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.3/jquery-ui.min.js"></script>
<input id="field" />
<button onclick="disable(false);">Autocomplete On</button>
<button onclick="disable(true);">Autocomplete Off</button>