两个下拉菜单

Two Drop Down Menus

我希望我可以使用 jQuery,但这必须在 JavaScript 中。我很感激你的帮助。 选择“空”(第一个下拉菜单)时,我需要第二个下拉菜单(a、b、c)中的所有值。 选择“1”时,我只需要a、b。 选择“ 2”时,我只需要b,c。

下拉菜单没问题。只需要更改值。我如何在 JavaScript?

中解决这个问题

第一个菜单

<onchange="first(this);>
<option value="empty"></option>
<option value="1">1</option>
<option value="2">2</option>

二级菜单

<id="second">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>

我更喜欢的一种解决方案是在 JS 中通过 CSS 将样式设置为 none。这样,该元素仍然存在,但它只是对查看器隐藏了。

您可以通过 [element-here].value 获取元素的值并将其与您想要的某个值进行比较。从那里,您将 select 您拥有的第二个下拉选项值和 运行 [element-here].style.display = "none"

我不推荐的另一种更复杂的方法是完全创建和销毁元素。类似于:

var x = document.createElement("option");
x.value = VALUE HERE;
parent.appendChild(document.createTextNode("TEXT HERE"))

这有点草率,但这是一种方法。您有一个数据数组,其中每个主要值都有有效的次要值。然后每次主列表更改时渲染它们。

let dropdownlist = [];
dropdownlist[1] = ['a', 'b', 'c'];
dropdownlist[2] = ['b', 'c'];

let select = document.createElement('select');

document.getElementById('myItemList').appendChild(select);

let x = 1;

document.getElementById('firstddl').addEventListener('change', (e) => {
  //console.log(e.target.value);
  x = e.target.value;
  select.innerHTML = '';
  renderDDL(dropdownlist, x)

});

function renderDDL(dropdownlist, x) {
  dropdownlist[x].forEach(function(item) {
    let option = document.createElement('option');
    select.appendChild(option);

    option.innerHTML += item;
  });
}

renderDDL(dropdownlist, x); // Runs once
<select id="firstddl">
  <option value=1>1</option>
  <option value=2>2</option>
</select>


<div id="myItemList">

</div>