javascript - JQuery自动完成返回空白结果
问题描述
我正在使用 jquery 自动完成和来自远程源的一些 geojson 数据。问题是结果列表是空白的。我猜这可能是数据格式问题。当用户搜索某些内容时,我只需要在自动完成时显示“标签”字段。
$(function() {
function log(message) {
$("<div>").text(message).prependTo("#log");
$("#log").scrollTop(0);
}
$('#birds').autocomplete({
source: function(request, response) {
$.getJSON("https://geosearch.planninglabs.nyc/v1/autocomplete?text=" + request.term, function(data) {
response($.each(data.features, function(key, value) {
console.log(value.properties.label);
return {
label: value.properties.label,
value: key
};
}));
});
},
minLength: 2,
delay: 100
});
});
.ui-autocomplete-loading {
background: white url("images/ui-anim_basic_16x16.gif") right center no-repeat;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="ui-widget">
<label for="birds">Birds: </label>
<input id="birds">
</div>
<div class="ui-widget" style="margin-top:2em; font-family:Arial">
Result:
<div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
</div>
解决方案
我想你可能有点$.each()
困惑$.map()
。考虑以下代码:
$(function() {
function log(message) {
$("<div>").text(message).prependTo("#log");
$("#log").scrollTop(0);
}
$('#birds').autocomplete({
source: function(request, response) {
$.getJSON("https://geosearch.planninglabs.nyc/v1/autocomplete?text=" + request.term, function(data) {
var results = [];
$.each(data.features, function(key, value) {
console.log(value.properties.label);
results.push({
label: value.properties.label,
value: key
});
});
response(results);
});
},
minLength: 2,
delay: 100
});
});
.ui-autocomplete-loading {
background: white url("images/ui-anim_basic_16x16.gif") right center no-repeat;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="ui-widget">
<label for="birds">Birds: </label>
<input id="birds">
</div>
<div class="ui-widget" style="margin-top:2em; font-family:Arial">
Result:
<div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
</div>
如您所见,return
不需要$.each()
. 它为数据源中的每个项目执行函数。您想构建一个结果数组,response()
一旦获得所有结果,就可以将其传回。
希望这可以帮助。
推荐阅读
- heroku - Laravel 无法访问数据库
- dashboard - 导出 Zabbix 仪表板
- javascript - react-spring:过渡组件问题
- angular - 如何从Angular8(独立组件)中的另一个组件传递一个组件的值
- android - 如何使用 Glide 加载 gif 图片 url?
- javascript - JavaScript 中静态变量的工作
- c++ - 从 C++ 中的文本文件中删除和更新产品
- mysql - ALTER VIEW 只为一个视图插入数据库前缀
- sql - 如何通过使用 JPA 或 Hibernate 中的标准构建器连接同一个表来选择值
- android - 未找到 com.google.android.gms.internal.zzeku 的类文件