如何根据选择值填充数组中的选择选项?

时间:2017-07-07 19:39:02

标签: javascript arrays select var

尝试根据第一个select元素的值从数组中填充第二个select元素的选项。我似乎无法理解为什么它只填充第一个选择元素的数组中的项目。我知道appendChild会导致项目在需要时继续进行,但我已经尝试清除变量,但似乎创建的选项元素仍然存在。

任何帮助都会很棒,谢谢!

<select id="makeSelect" onChange="modelAppend()">
    <option value="merc">Mercedes</option>
    <option value="audi">Audi</option>
    <option value="bmw">BMW</option>
</select>

<select id="modelSelect">

</select>

<script>
var audiModels = ["TT", "R8", "A4", "A6"]; //audimodels
var mercModels = ["C230", "B28", "LTX",]; //mercmodels
var bmwModels = ["328", "355", "458i",]; //bmwmodels
var selectedMake = document.getElementById("makeSelect"); //grabs the make select
var selectedModel = document.getElementById("modelSelect"); //grabs the model select
var appendedModel = window[selectedMake.value + "Models"]; // appends "Models" to selectedMake.value and converts string into variable

function modelAppend() {
    for (var i = 0; i < appendedModel.length; i ++) { // counts items in model array
        var models = appendedModel[i]; // // sets "models" to count of model array
        var modelOptions = document.createElement("option"); //create the <option> tag
        modelOptions.textContent = models; // assigns text to option
        modelOptions.value = models; // assigns value to option
        selectedModel.appendChild(modelOptions); //appeneds option tag with text and value to "modelSelect" element
    }
}

</script>

1 个答案:

答案 0 :(得分:1)

这条线很可疑:

var appendedModel = window[selectedMake.value + "Models"];

您需要在值更改时获取元素,而不是在页面加载时获取。然后,您还需要删除更改选项,或者如果用户多次选择,您将获得一个很长的列表。使用对象存储数组,以便以后更容易访问它们。也更好地使用事件监听器而不是内联js(尽管这不是主要问题)。

尝试以下代码:

&#13;
&#13;
let models = {
  audiModels: ["TT", "R8", "A4", "A6"],
  mercModels: ["C230", "B28", "LTX"],
  bmwModels: ["328", "355", "458i"]
}

document.getElementById('makeSelect').addEventListener('change', e => {
  let el = e.target;
  let val = el.value + 'Models';
  let appendTo = document.getElementById('modelSelect');
  Array.from(appendTo.getElementsByTagName('option')).forEach(c => appendTo.removeChild(c));
  if (!models[val] || !Array.isArray(models[val])) {
    appendTo.style.display = 'none';
    return;
  }
  models[val].forEach(m => {
    let opt = document.createElement('option');
    opt.textContent = opt.value = m;
    appendTo.appendChild(opt);
  });
  appendTo.style.display = '';
});
&#13;
<select id="makeSelect">
    <option value=""></option>
    <option value="merc">Mercedes</option>
    <option value="audi">Audi</option>
    <option value="bmw">BMW</option>
</select>

<select id="modelSelect" style="display:none">

</select>
&#13;
&#13;
&#13;