我有这样的代码:
<label>Brand</label></br>
<select name="brand" id="brand" onChange="changecat(this.value);">
<option value="" selected>Select Brand</option>
<option value="A">AMD</option>
<option value="B">Intel</option>
</select></br></br>
<label>Socket</label></br>
<select name="category" id="category" onchange="showProcessor()">
<option value="" disabled selected>Select Socket</option>
</select>
var brandByCategory = {
A: ["AM4", "AM3", "AM2"],
B: ["LGA 1151", "LGA 1151v2", "LGA 1150"]
}
function changecat(value) {
if (value.length == 0)
document.getElementById("category").innerHTML = "<option>Select Socket</option>";
else {
var catOptions = "";
for (categoryId in brandByCategory[value]) {
catOptions += "<option>" + brandByCategory[value][categoryId] + "</option>";
}
document.getElementById("category").innerHTML = catOptions;
}
}
如果选择了品牌选项,那么它将填充套接字下拉列表,并且可以正常工作,但是套接字下拉选项没有值,我必须为其赋予一个值,因为我想获取数据从需要品牌价值的数据库中获取。如何在第二个下拉菜单中增加价值?
最佳答案
var brandByCategory = {
A: ["AM4", "AM3", "AM2"],
B: ["LGA 1151", "LGA 1151v2", "LGA 1150"]
}
function changecat(value) {
if (value.length == 0) {
document.getElementById("category").innerHTML = "<option>Select Socket</option>";
} else {
var catOptions = "";
for(categoryId in brandByCategory[value]){
catOptions += `<option value="${brandByCategory[value][categoryId]}">${brandByCategory[value][categoryId]}</option>`;
}
console.log(catOptions)
document.getElementById("category").innerHTML = catOptions;
}
}
changecat('A')
关于javascript - 在javascript函数中为html添加值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58516592/