繁体   English   中英

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

[英]How do I set input list dropdown dynamically using JavaScript?

我见过这个问题,但它已经很老了,很多事情都发生了变化。

我希望能够在我的 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>的 function 。 然后,您需要做的就是在您的国家/地区数组准备好时调用 function:

 // 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", "Russia", "Germany", "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>

暂无
暂无

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

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