1 回答
TA贡献1786条经验 获得超13个赞
对此代码应用干哲学
这只是一个测试,但它是您正在寻找的行为吗?
HTML代码
<form class="form">
<div class="form-group">
<select id="collections" name="collection">
<option>Select a value</option>
<option value="man">Man</option>
<option value="woman">Woman</option>
</select>
<select id="box2" name="collections-items">
</select>
</div>
</form>
JS代码
let chooseCollections = document.querySelector('#collections')
let selectItems = document.querySelector('#box2')
let manCollection = {
categories: ["Shoes", "Shirt"]
}
let womanCollection = {
categories: ["Dress", "Shirt"]
}
chooseCollections.addEventListener('change', (e) => {
selectItems.querySelectorAll('*').forEach(el => el.remove());
selectItems.style.display = "none"
if(e.target.value === "man") {
selectItems.style.display = "block"
for(let i = 0; i < manCollection.categories.length; i++) {
var option = document.createElement('option')
var value = manCollection.categories[i]
option.value = value
option.innerHTML = value
selectItems.appendChild(option)
}
}
if(e.target.value === "woman") {
selectItems.style.display = "block"
for(let i = 0; i < womanCollection.categories.length; i++) {
var option = document.createElement('option')
var value = womanCollection.categories[i]
option.value = value
option.innerHTML = value
selectItems.appendChild(option)
}
}
})
CSS
#box2 {
display: none;
}
我将 manCollection 和 womanCollection 表示为您数据库中的数据。此代码未优化,可以更高效,但您可以从它开始。
- 1 回答
- 0 关注
- 108 浏览
添加回答
举报