javascript - 交互式更新下拉列表
问题描述
我想实现那些下拉菜单,当您选择以前的输入时数据会更新,例如您选择Sony
“品牌”,然后您获得所有Sony
电视型号..然后该型号的所有变体,我有所有数据数组,但最初它在空气表上(类似csv))不知道如何处理它,我应该保存参数并向下工作还是有一些库可以使这项任务更容易?谢谢,任何建议表示赞赏
解决方案
如果您提供您当前的尝试是很有帮助的,这样我们就可以知道您实际上正在尝试实现什么。
这是使用 JS的级联下拉列表的一个非常基本的示例
const data = [
{ brand: 'Brand A', models: [ 'model a1', 'model a2', 'model a3' ] },
{ brand: 'Brand B', models: [ 'model b1', 'model b2', 'model b3' ] },
{ brand: 'Brand C', models: [ 'model c1', 'model c2', 'model c3' ] },
{ brand: 'Brand D', models: [ 'model d1', 'model d2', 'model d3' ] },
];
const brands = document.getElementById('brands');
const models = document.getElementById('models');
// Populate the Brands dropdown from the data set
data.forEach( d => {
const option = document.createElement('option');
option.value = d.brand;
option.innerText = d.brand;
brands.append(option);
});
// Anytime the Brand changes, repopulate the models
// dropdown based off the selected brand
brands.addEventListener('change', e => {
const val = e.target.value;
const brand = data.find( d => d.brand === val);
models.innerHTML = '';
brand.models.forEach( m => {
const option = document.createElement('option');
option.value = m;
option.innerText = m;
models.append(option);
});
});
<div>
<label>Brand</label>
<select id="brands">
<option>Select</option>
<!-- options are dynamic -->
</select>
</div>
<div>
<label>Model</label>
<select id="models">
<!-- options are dynamic -->
</select>
</div>
推荐阅读
- spring - 通过 Zuul 网关访问路由时不考虑用户的权限/角色
- javascript - 覆盖本地存储而不是添加新元素 (JavaScript)
- javascript - 如何限制 ng 引导模式的 ng-deep 类?
- api-platform.com - 无实体操作
- javascript - 如何使用 vanilla JS 复制 useState
- javascript - 映射函数不起作用未处理的拒绝(TypeError):fieldsList.map 不是函数
- javascript - div 中的 SweetAlert2
- git - 为克隆的存储库安装 requirements.txt 时出现错误消息
- java - 我正在使用 Android Studio 4.1,但我无法解决问题。请看下面的代码
- javascript - 如何使用 HTML 和 CSS 将 div 放在图像上?