微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何使用 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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?