【发布时间】:2021-08-24 12:36:29
【问题描述】:
我在数据库中有一个包含所有城市(大约 41.000)的表,我需要用户选择一个。当输入中的字符大于 3 时,数据列表被填充但结果无法被选中。
我在 PHP 中进行了一个 API 调用,它为填充数据列表的 javascript 提供了一个 JSON。 每次触发事件时,数据列表都会不断填充,复制结果。
我知道我肯定遗漏了一部分代码。我使用了一些教程,但没有提到这个问题。我该怎么办?我在下面粘贴了一些代码。
html:
<input name="locationFrom" id="locationFrom" type="text" class="form-control" required="required" autocomplete="off" list="countriesFrom-<?=$i?>" onkeyup="findCity(this.value, <?=$i?>)">
<datalist id="countriesFrom-<?=$i?>"></datalist>
js:
function findCity(citySearch, j){
if (citySearch.length > 3) {
$.ajax({
url: './api/country/find.php?city=' + citySearch,
type: 'GET',
contentType: 'application/json; charset=utf-8',
dataType: 'JSON',
success: function(response){
var len = response['records'].length;
var countries = response['records'];
for(var i=0; i<len; i++){
var city = countries[i].city;
var region = countries[i].region;
var country = countries[i].country;
$("#countriesFrom-" + j).append($("<option >").attr('value', city)
.text(city + ", " + region + ", " + country));
}
}
});
}
}
【问题讨论】:
标签: javascript html dom event-handling