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 關注
- 129 瀏覽
添加回答
舉報