如何使用 JavaScript 动态设置输入列表下拉列表? 运行这个

问题描述

我看过this question,但它已经很旧了,很多东西都变了。

我希望能够在我的 JS 代码中创建一个虚拟数据列表,并以某种方式将其链接#countryInput,以便这些国家/地区显示为下拉列表。我不想为这个简单的事情生成 HTML。

如果这是不可能的或类似的事情,有没有更好的方法来做到这一点?因为当您处理链接数据列表等时它会变得混乱。

运行这个。

代替那个硬编码示例,我如何创建这个下拉列表而不为每个国家/地区实际生成凌乱的 HTML?如果有 100 个国家,HTML 文件会越来越大,比如说每个国家有 10 个城市...

// These countries need to be displayed as a dropdown in the input field
const countries = ["Canada","Russia","Germany","Italy"];

// This is that input field
const countryInput = document.getElementById('countryInput');
<input type="text" list="countriesDataList" id="countryInput" />

<!-- Hard coded  -->
<datalist id="countriesDataList">
    <option>Canada</option>
    <option>Russia</option>
    <option>Germany</option>
    <option>Italy</option>
</datalist> 

解决方法

您可以创建一个动态填充 <datalist> 的函数。您需要做的就是在您的国家/地区数组准备就绪时调用该函数:

// These countries need to be displayed as a dropdown in the input field
const countries = ["Canada","Russia","Germany","Italy"];

// This is that input field
const countryInput = document.getElementById('countryInput');

// This is the datalist
const datalist = document.getElementById('countriesDataList');

function populateList(arr) {
  arr.forEach(country => {
    var option = document.createElement("option");
    option.innerHTML = country;
    datalist.appendChild(option);
  });
}

populateList(countries);
<input type="text" list="countriesDataList" id="countryInput" />

<datalist id="countriesDataList"></datalist>

每当您的国家/地区数组发生变化时,只需再次调用 populateList

,

像这样

您可以在列表更改时对城市列表进行ajax

// These countries need to be displayed as a dropdown in the input field
const countries = ["Canada","Italy"];

// This is that input field
const countryInput = document.getElementById('countryInput');
document.getElementById('countriesDataList').innerHTML = countries
  .map(country => `<option>${country}</option>`).join("");
<input type="text" list="countriesDataList" id="countryInput" />

<!-- Hard coded  -->
<datalist id="countriesDataList">

</datalist>

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...