首页 > 解决方案 > 交互式更新下拉列表

问题描述

我想实现那些下拉菜单,当您选择以前的输入时数据会更新,例如您选择Sony“品牌”,然后您获得所有Sony电视型号..然后该型号的所有变体,我有所有数据数组,但最初它在空气表上(类似csv))不知道如何处理它,我应该保存参数并向下工作还是有一些库可以使这项任务更容易?谢谢,任何建议表示赞赏

e

标签: javascriptreact-nativelogicdataflow

解决方案


如果您提供您当前的尝试是很有帮助的,这样我们就可以知道您实际上正在尝试实现什么。

这是使用 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>


推荐阅读