select JS原生 / jQuery獲取選中值、設定當前選項等
阿新 • • 發佈:2018-11-08
JS原生版:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <select name="" id="s1" onchange="getVal()"> <option value="1" data-val="a">11111</option> <option value="2" data-val="b">22222</option> <option value="3" data-val="c">33333</option> </select> <script> var currentSel = document.getElementById('s1'); var index = currentSel.selectedIndex; //獲取選中的索引值 console.log( index ); console.log( currentSel.options[index].text ); //獲取選中的文字 console.log( currentSel.options[index].value ); //獲取選中的值 </script> </body> </html>
jQuery版:
<script src="../jquery-1.12.4.min.js"></script> <script> function getVal() { //獲取選中值 value // console.log($("#s1").val()); //獲取選中文字 // console.log($("#s1").find("option:selected").text()); // 或 // console.log($("#s1 option:selected").text()); //獲取選中的屬性值 // console.log($("#s1").find("option:selected").attr("data-val")); // 或 // console.log($("#s1 option:selected").attr("data-val")); //獲取選中的索引: //console.log($("#s1").get(0).selectedIndex); } function setVal() { //設定選中項 //$("#s1").val(2); // 或 $("#s1").get(0).selectedIndex =2; } $(document).ready(function () { setVal(); }) </script>