如何解决如何使用 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>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。