如何在特定击键后启用 iQuery 自动完成?

How to enable iQuery autocomplete after specific keystrokes?

我正在使用 jQuery 自动完成功能。我只想 运行 仅当输入的数字超过 2 位时才使用自动完成功能。以下是我的尝试:

    $(function() {
        $('#postcode').on('input', function() {
            var val = $(this).val();


            if(val.length > 2) {
                $( "#postcode" ).autocomplete({
                    source: function( request, response ) {
                        $.ajax({
                            url: "<?php echo base_url('welcome/read_postcode') ?>",
                            dataType: "jsonp",
                            data: {
                                q: request.term
                            },
                            success: function( data ) {
                                response( data );
                            }
                        });
                    }
                });
            }
        });
    });

代码运行很好,没有错误。但结果并不如预期。另外,当我将 alert(); 放在 if() 条件中时,结果符合预期,但不是自动完成部分。怎么了?

更新:使用此代码发生的事情是,当输入第四个数字时自动完成功能 运行s 然后,它在每次击键时 运行s 直到该字段中的数字为零.

此处正确的方法是使用自动完成的 minLength 设置:

$( "#postcode" ).autocomplete({
  minLength: 2
});

http://api.jqueryui.com/autocomplete/#option-minLength

您的初始代码之所以如此,是因为调用 autocomplete() 实际上会将事件处理程序附加到元素。您在这里所做的是等待输入超过 2 个字符,然后然后 附加一个新事件。随后的击键会触发自动完成,这就是为什么您会看到 4 个字符及之后的结果。

这与以最小字符长度触发自动完成 ajax 请求不同 - 这是 minLength 参数的用途。希望这有助于解释事情。

您可以使用 minLength

minLength: The minimum number of characters a user has to type before the Autocomplete activates. Zero is useful for local data with just a few items. Should be increased when there are a lot of items, where a single character would match a few thousand items.

$(function () {
    $("#postcode").autocomplete({
        source: function (request, response) {
            $.ajax({
                url: "<?php echo base_url('welcome/read_postcode') ?>",
                dataType: "jsonp",
                data: {
                    q: request.term
                },
                success: function (data) {
                    response(data);
                }
            });
        },
        minLength: 2
    });
});

Working example