首页 > 解决方案 > 使用 VanillaJS 的动态下拉菜单

问题描述

由于在 Bootstrap 5 中不再需要 JQuery,我想用 VanillaJS 替换我的 Dynamic Dropdowns。

document.addEventListener('DOMContentLoaded', function () {

const optgroups1 = document.getElementById('pos_select').getElementsByTagName('optgroup');
  let sel = document.getElementById('candidate_functionalarea_id');
  sel.addEventListener("change", function () {
    let evnt = document.getElementById("candidate_functionalarea_id");
    let options = dyndrop(optgroups1, evnt);
    document.getElementById('candidate_positioncategory_id').innerHTML = options;
  });

  const optgroups2 = document.getElementById('tag_select').getElementsByTagName('optgroup');
  let sel2 = document.getElementById('candidate_function_id');
  sel2.addEventListener("change", function () {
    let evnt2 = document.getElementById("candidate_functionalarea_id");
    let options = dyndrop(optgroups2, evnt2);
    document.getElementById('candidate_positioncategory_id').innerHTML = options;
  });

  function dyndrop(optgroups, evnt) {
    let option_text = evnt.options[evnt.selectedIndex].text;
    let option_id = evnt.options[evnt.selectedIndex].value;
    let options;
    for (let i = 0; i < optgroups.length; i++) {
      if (optgroups[i].label == option_text) {
        options = optgroups[i].innerHTML;
      }
    }
    return options;
  };
});

当我在console.log中查看optgroup1和optgroup2的内容时,我看到这两个变量仍然正确填写在candidate_functionalarea_id的第一个选择中( HTMLCollection { 0: optgroup, 1: optgroup, 2: optgroup, length: 3 } ) . 一切运行完美。但是一旦我选择了另一个candidate_functionalarea_id,optgroup1和optgroup2中就没有属性了(内容:HTMLCollection {长度:0})。

如果有一种方法不能改变 optgroup1 和 optgroup2,我会解决这个问题。

标签: javascriptruby-on-rails

解决方案


推荐阅读