繁体   English   中英

如何使用 vanilla javascript 用数组的内容填充 html select 元素?

[英]How can I populate a html select element with the contents of an array using vanilla javascript?

我正在创建一个基本的天气应用程序。

我创建了一个由两个<select>元素组成的简单模式。 一个用于城市,另一个用于国家。

<div class="modal">
  <select name="city" id="city"></select>
  <select name="country" id="country"></select>
</div>

使用香草 JavaScript,我想用存储在其他脚本中的值 arrays 填充这些元素。

export const countries = [
    { Code: "AF", Name: "Afghanistan" },
    { Code: "AX", Name: "\u00c5land Islands" },
    { Code: "AL", Name: "Albania" },
    { Code: "DZ", Name: "Algeria" },
    { Code: "AS", Name: "American Samoa" },
    { Code: "AD", Name: "Andorra" },
    { Code: "AO", Name: "Angola" },
    { Code: "AI", Name: "Anguilla" },
    { Code: "AQ", Name: "Antarctica" },
    { Code: "AG", Name: "Antigua and Barbuda" },
    { Code: "AR", Name: "Argentina" }, //etc etc
export const cities = [
  {
    country: 'Andorra',
    geonameid: 3040051,
    name: 'les Escaldes',
    subcountry: 'Escaldes-Engordany',
  },
  {
    country: 'Andorra',
    geonameid: 3041563,
    name: 'Andorra la Vella',
    subcountry: 'Andorra la Vella',
  },
  {
    country: 'United Arab Emirates',
    geonameid: 290594,
    name: 'Umm al Qaywayn',
    subcountry: 'Umm al Qaywayn',
  }, //etc etc

这是我的模式的脚本,它正在导入citiescountries变量。 这是我尝试过的方法,但是 select 元素保持空白并且控制台中没有出现错误。 我什至尝试将变量记录到控制台,但什么也没有出现。 我还尝试向按钮添加点击事件侦听器,但没有任何区别。

模态.js

import { cities } from "./cityData.js";
import { countries } from "./countryData.js";

const selectCity = document.getElementById('city')
const selectCountry = document.getElementById('country')

window.onload = function() {
  let cityOptions = cities.map(city => `<option value=${city.name.toLowerCase()}>${city.name}</option>`).join('\n');
  let countryOptions = countries.map(country => `<option value=${country.Code.toLowerCase()}>${country.Code}</option>`).join('\n')

  selectCity.innerHTML = cityOptions;
  selectCountry.innerHTML = countryOptions;
}

编辑:抱歉,我应该澄清一下,目前模态实际上不是模态,它只是我的 html 中的一个 static div。它加载了页面的 rest。

你的方法是正确的,你可以看到它在这里工作。

也许您的脚本没有执行,您确定要将 JS 添加到 HTML 文件中吗?

 const countries = [ { Code: "AF", Name: "Afghanistan" }, { Code: "AX", Name: "Åland Islands" } ] const selectCountry = document.getElementById('country') window.onload = function() { let countryOptions = countries.map( country => `<option value=${country.Code.toLowerCase()}>${country.Code}</option>`).join('\n') selectCountry.innerHTML = countryOptions; }
 <div class="modal"> <select name="country" id="country"></select> </div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM