操作下拉框時,獲取當前選中項的文本、值與索引是最基本的需求。下面分別介紹原生 JavaScript 與 jQuery 的寫法。
var obj = document.getElementById("testSelect"); //定位id var index = obj.selectedIndex; // 選中索引 var text = obj.options[index].text; // 選中文本 var value = obj.options[index].value; // 選中值
$('#testSelect option:selected').text();//選中的文本 $('#testSelect option:selected').val();//選中的值 $("#testSelect").get(0).selectedIndex;//索引
$("#testSelect").find("option:selected").text();//選中的文本 $("#testSelect").find("option:selected").val();//選中的值 $("#testSelect").find("option:selected").get(0).selectedIndex;//索引
三種方式效果一致,可按團隊習慣選擇。希望這份整理能給你帶來參考。