最近要用到Jquery對Select的操作,總結一下,以備參考:
- 獲取Select長度: $(”#select option”).length、所選長度:$(”#select option:selected”).length or size()
- 取得序號
$(”#select option”).index($(”#select option:selected”)) - 獲取Option顯示的文字:$(”#select option:eq(”+i+”)”).text() – i是option的序號
- 獲取Option的value:$(”#select option:eq(”+i+”)”).val() 或者attr(”value”)
- 清除所有Option:$(”#select”).html(””);
- 刪除Option
$(”#select option:eq(”+i+”)”).replaceWith(””); – i是option的序號
$(”#select option:eq(”+i+”)”).remove(); - 改變選擇的Option
$(‘#select option:selected’).removeAttr(‘selected’);
$(‘#select option[value='+i+']‘).attr(‘selected’,'selected’); - 增加Option
$(”<option value=’”+value+”‘>”+name+”</option>”).appendTo(”#select”); - 通過value選定Option
- $(”#select”).val(”zhaiduo”).attr(”selected”, ”selected”);