如何在jQuery UI自动完成中实现"mustMatch"和"selectFirst"?

doc*_*day 38 jquery jquery-ui autocomplete

我最近将一些自动完成插件从bassistance生成的插件迁移到了jQuery UI自动完成.

如何在不修改核心自动完成代码本身的情况下,仅使用回调和其他选项实现"mustMatch"和"selectFirst"?

doc*_*day 40

我想我解决了这两个问题......

为了简化操作,我使用了一个常见的自定义选择器:

$.expr[':'].textEquals = function (a, i, m) {
    return $(a).text().match("^" + m[3] + "$");
};
Run Code Online (Sandbox Code Playgroud)

其余代码:

$(function () {
    $("#tags").autocomplete({
        source: '/get_my_data/',
        change: function (event, ui) {
            //if the value of the textbox does not match a suggestion, clear its value
            if ($(".ui-autocomplete li:textEquals('" + $(this).val() + "')").size() == 0) {
                $(this).val('');
            }
        }
    }).live('keydown', function (e) {
        var keyCode = e.keyCode || e.which;
        //if TAB or RETURN is pressed and the text in the textbox does not match a suggestion, set the value of the textbox to the text of the first suggestion
        if((keyCode == 9 || keyCode == 13) && ($(".ui-autocomplete li:textEquals('" + $(this).val() + "')").size() == 0)) {
            $(this).val($(".ui-autocomplete li:visible:first").text());
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

如果您的任何自动填充建议包含regexp使用的任何"特殊"字符,则必须在自定义选择器中的m [3]中转义这些字符:

function escape_regexp(text) {
  return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
Run Code Online (Sandbox Code Playgroud)

并更改自定义选择器:

$.expr[':'].textEquals = function (a, i, m) {
  return $(a).text().match("^" + escape_regexp(m[3]) + "$");
};
Run Code Online (Sandbox Code Playgroud)


小智 34

我使用像mustMatch这样简单的东西,它的工作原理.我希望它对某人有帮助.

        change: function (event, ui) {
            if (!ui.item) {
                 $(this).val('');
             }
        }
Run Code Online (Sandbox Code Playgroud)

  • 请注意,你应该确保你有'autoFocus:true` (2认同)