JQuery和JS—操作select

<select name="sort" id="sort">
    <option value="desc">按日期倒序</option>
    <option value="asc">按日期正序</option>
</select>

JQuery部分

1.根據(jù)value設(shè)置選中

$("#sort").val("asc")

2.根據(jù)text設(shè)置選中

$("#sort").find("option[text=按日期正序]").attr("selected",true);

3.獲取選中項(xiàng)的value

$("#sort").val()

4.獲取選中項(xiàng)的text

$("#sort").find("option:selected").text();
或
$("#sort option:selected").text();

5.改變選項(xiàng),進(jìn)行相應(yīng)操作(多用于級(jí)聯(lián))

$("#sort").change(function(){
      //   操作
})

6.判斷是否被選中

$("option[value=desc]").is(':checked') //true為被選中,false未被選中
$("option[value=desc]").attr('selected')!=undefined  //true為被選中,false未被選中

7.獲取select選中的索引

$("#sort").get(0).selectedIndex  //下表從0開始

8.添加option

$("#sort").append("<option  value=" + value + ">" + text + "</option>");
  • 二、JS部分

var   mySelect = document.getElementById("sort");//定位id(獲取select)
var   index =mySelect.selectedIndex;// 選中索引(選取select中option選中的第幾個(gè))
var   text =mySelect.options[index].text; // 選中文本
var   value =mySelect.options[index].value; // 選中值
mySelect.options[index].selected // 判斷select中的某個(gè)option是否選中   true為選中   false 為未選中
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容