今天为大家分享一篇js动态设置select下拉菜单的默认选中项实例,具有很好的参考价值,希望对大家有所帮助。
代码实例如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <select id="box"> <option value ="volvo">Volvo</option> <option value ="saab">Saab</option> <option value="opel">Opel</option> <option value="audi">Audi</option> </select> <button id="btn">设置</button> </body> </html> <script> // 根据指定内容设置下拉框的内容 111|222|333|444 let btn = document.querySelector('#btn') btn.onclick = () =>{ setselectchooseditem('box','222|我的|她') } // 封装函数 function setselectchooseditem (idStr, text) { let $id = document.getElementById(idStr) let str = text let arr = str.split('|') let output = '' for (let i in arr) { output += `<option value="">${arr[i]}</option>` } $id.innerHTML = output } </script>