我正在使用 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()
条件内时,结果符合预期,但不是自动完成部分。出了什么问题?
更新:使用此代码时,自动完成功能会在输入第四个数字时运行,然后在每次击键时运行,直到该字段中的数字为零。
最佳答案
您可以使用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
});
});
关于jquery - 如何在特定按键后启用 iQuery 自动完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44276369/