我是新来的,所以如果我听起来很卑鄙,请原谅.

我正在try 用HTML语言创建下拉框来填充存储在JSON文件中的国家/地区列表.国家/地区的名称在对象中的另一个对象的数组中的对象中找到.

我已经设法填充了下拉框中的国家/地区,但它们似乎是重复的,并且没有按字母顺序排列.

我try 使用.sort(),但不确定如何在不 destruct 代码的情况下使用.

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脚本.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)
             );
             
            })
        }
    });

一个JSON文件的样例,名为Country Borders.Geo.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 ]]}, 
...

以此类推

pic of what my dropdown box looks like

如有建议,我们将不胜感激!期待中的感谢!

推荐答案

您可以这样实现它:

<span id="selectContainer">
  <select name="country" id="country" class="form-select">
    <option value="">Select a country</option>
  </select>
</span>

和你的 playbook :

$.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])
    );
  }
});

Javascript相关问答推荐

Snowflake - .toISOString()错误地舍入JS存储过程中的时间戳

我无法使用tailwind-css和reactJS修改图像的位置

使用CDO时如何将Vue组件存储在html之外?

如何让\w token 在此RegEx中表现得不贪婪?

使用useParams路由失败

如何从对象嵌套数组的第二级对象中过滤出键

如何编辑代码FlipDown.js倒计时?

React:未调用useState变量在调试器的事件处理程序中不可用

Javascript,部分重排序数组

我不知道为什么setwritten包装promise 不能像我预期的那样工作

网页自检测外部元素无法加载

点击按钮一次有文本出现和褪色,而不是点击两次?(html,CSS,JavaScript)

单击ImageListItemBar的IconButton后,在Material—UI对话框中显示图像

用于编辑CSS样式的Java脚本

如何在Angular拖放组件中同步数组?

如何在HTMX提示符中设置默认值?

未捕获的运行时错误:调度程序为空

第一项杀死下一项,直到数组长度在javascript中等于1

Next.js无法从外部本地主机获取图像

Reaction useState和useLoaderData的组合使用引发无限循环错误