javascript - 使用 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,我会解决这个问题。
解决方案
推荐阅读
- heroku - 我无法部署到 vercel,因为我收到错误:Specified images.domains should be an Array of strings received invalid values ()
- python - 如何旋转 Tableau 中的所有列
- php - 在 Woocommerce 变量产品中的所有属性标签末尾添加一个红色星号
- discord.py - Discord.py - 在函数仍在运行时执行函数中的函数
- facebook-graph-api - Facebook API:无法安排视频
- flutter - 我在哪里可以保存 Android 和 IOS 上相机插件创建的视频文件?
- sql - SQL:如何使用多列分区计算百分比增加
- flutter - 仅使用 onTap 功能抖动不同的屏幕导航
- r - 如何使用 margins 包来评估因变量的不同值的边际影响
- wordpress - 我无法在 wordpress5.7 中安装 yoshizawa 主题