今天開發網站遇到一個小問題,如何動態通過js讓select控件選中指定的值呢?在調試過程中,發現了amazeui這個ui組件的問題,使用它個組件的樣式就無法通過selected=true設置為選中。
后來,去了官網查找了相關方法來實現,但是按照官網的代碼并不能達到選中效果,最后無奈只能將樣式去掉,使用HTML原有的樣式,手動通過JS來實現這個功能。

手動通過原生JS來實現:
/** * 設置select控件選中 * @param selectId select的id值 * @param checkValue 選中option的值 * @author 標哥 */ function set_select_checked(selectId, checkValue){ var select = document.getElementById(selectId); for (var i = 0; i < select.options.length; i++){ if (select.options[i].value == checkValue){ select.options[i].selected = true; break; } } }然后通過這樣來調用:
// 設置select選中該班組set_select_checked('edit-group', group_id);注意:不要傳'#edit-group',習慣了jquery,會出問題的~
問題雖然簡單,但是記錄下來,下次直接復制過來即可!
文章來源:http://tech.yunyingxbs.com/article/detail/id/343.html
新聞熱點
疑難解答