You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

HTML下拉框从JSON填充国家列表:重复值与未排序问题求助

问题解决:下拉框重复+未排序的修复

先拆解你代码里的核心问题:

  • 重复问题:外层循环result(也就是features数组)的同时,内层嵌套了$.each(data)遍历整个JSON对象。data包含type和features两个属性,导致每个国家被重复添加两次。
  • 排序问题:没有对国家列表做字母排序处理。
  • value值错误:val(item)里的item是data的属性值(比如第一次是字符串featureCollection,第二次是整个features数组),这不是有效的下拉框选项值,应该用国家的编码(比如iso_a2或iso_a3)。

修正后的完整代码:

$.getJSON("./countryBorders.geo.json", function (data) {
    // 1. 获取features数组
    let features = data.features;
    
    // 2. 按国家名称字母排序(忽略大小写)
    features.sort((a, b) => {
        const nameA = a.properties.name.toLowerCase();
        const nameB = b.properties.name.toLowerCase();
        if (nameA < nameB) return -1;
        if (nameA > nameB) return 1;
        return 0;
    });
    
    // 3. 遍历排序后的数组,添加选项到下拉框
    features.forEach(feature => {
        const countryName = feature.properties.name;
        const countryCode = feature.properties.iso_a2; // 可用iso_a3替代
        $('#country').append(
            $('<option></option>')
                .val(countryCode)
                .text(countryName)
        );
    });
});

补充说明:

  • 排序时转成小写是为了避免大小写导致的排序混乱(比如Bahamas和mexico的大小写差异)。
  • 如果你的JSON里存在重复国家数据(正常的countryBorders数据集不会有),可以先去重再排序:
    // 按国家名称去重
    const uniqueFeatures = [...new Map(features.map(item => [item.properties.name, item])).values()];
    // 再对uniqueFeatures执行后续排序和遍历逻辑
    

内容的提问来源于stack exchange,提问作者orionsquare2000

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 07:05:32