当选择列表时,子列表不会在HTML/JavaScript网页中刷新



我正在为一个网站编写一个机器人程序。我一直在选择子列表。我可以为一个列表设置一个值,但不幸的是,其他列表不会通过所选列表更新。

例如;A";类别到值";B";使用CCD_ 1但是子列表没有用"0"更新;B";模型。

我正在使用Chrome控制台来检查我的编码验证。

这是一件非常琐碎的事情,它实际上取决于从哪里加载派生选项以及如何加载(从服务器获取,包括在DOM中等(。通常,列表是以JSON的形式动态加载的,您将对其进行解析,并用相应的值填充选择框。

这里有一个小例子,说明了实现这一点的多种方法之一——我假设您理解values是您正在使用并从服务器加载的所有必需值:

//Load the required values from server or add them to the page statically:
//You can also fetch them one by one... you get the point.
var values = { 
fruits : [
{ value : "apple", text : "Apple"},
{ value : "orange", text : "Orange"}
],
drinks : [
{ value : "lemonade", text : "Lemonade"},
{ value : "water", text : "Water"},
{ value : "coffee", text : "Coffee"},
{ value : "tea", text : "Tea"}
]
};
//The dropdown:
let dropdown = document.getElementById('main-list');
//Attach a `change` event handler:
dropdown.addEventListener(
'change',
function() { 

//Clear the populate list first:
const populate = document.getElementById('populate');
populate.innerText = null;

//The selected value - which defines what to load:
const load = this.value;

//Add the options to the populate select element:
for (const opt of (values[load] || [])) {
let option = document.createElement('option');
option.text = opt.text;
option.value = opt.value;
populate.add(option);
}
},
false
);
<select id="main-list">
<option value="none">Please select</option>
<option value="fruits">Fruits</option>
<option value="drinks">Drinks</option>
</select>
<select id="populate">
</select>

找到答案:

document.querySelector('#id').dispatchEvent(new Event('change', { 'bubbles': true }))

最新更新