我是新来的,所以如果我听起来很卑鄙,请原谅。
我正在尝试在 HTML 中创建一个下拉框来填充存储在 JSON 文件中的国家/地区列表。国家/地区的名称可在对象数组中的另一个对象中的对象中找到。
我已成功填充下拉框中的国家/地区,但它们看起来重复且不按字母顺序排列。
我尝试使用 .sort() 但不知道如何在不破坏我的代码的情况下。
index.html
<span id="selectContainer">
<select name="country" id="country" class="form-select">
<!-- populate from PHP call that returns only the codes and names from the countryborder GeoJSON file -->
<option value="">Select a country</option>
</select>
</span>
脚本.js
$.getJSON("./countryBorders.geo.json", function(data) {
const result = data['features'];
for (let i=0; i < result.length; i++){
let name = result[i]['properties']['name'];
$.each(data, function (key, item) {
$('#country').append(
$('<option></option>')
.val(item)
.html(name)
);
})
}
});
名为countryBorders.geo.json的 JSON 文件示例
{"type": "featureCollection", "features":
[{"type": "Feature", "properties": {"name": Bahamas", "iso_a2":"BS", "iso_a3": "044"}, "geometry": {"type": "Multipolygon", "coordinates": [[ etc ]]},
{"type": "Feature", "properties": {"name": Mexico", "iso_a2":"MX", "iso_a3": "484"}, "geometry": {"type": "Multipolygon", "coordinates": [[ etc ]]},
{"type": "Feature", "properties": {"name": Trinidad and Tobago", "iso_a2":"TT", "iso_a3": "780"}, "geometry": {"type": "Multipolygon", "coordinates": [[ etc ]]},
...
等等
任何建议将不胜感激!谢谢期待!
你可以这样实现:
<span id="selectContainer">
<select name="country" id="country" class="form-select">
<option value="">Select a country</option>
</select>
</span>
你的脚本:
$.getJSON("./countryBorders.geo.json", function(data) {
const result = data['features'];
let countryNames = [];
// Populate the countryNames array
for (let i = 0; i < result.length; i++) {
let name = result[i]['properties']['name'];
countryNames.push(name);
}
// Sort the country names
countryNames.sort();
// Populate the dropdown
for (let i = 0; i < countryNames.length; i++) {
$('#country').append(
$('<option></option>')
.val(countryNames[i])
.html(countryNames[i])
);
}
});