一、selected="selected"
HTML通過<select>的屬性來設置選中項,
此方法也可以在動態語言在后台根據需要控制輸出結果。
<select ID='sel' class="form-control width150"> <option value="1">開啟</option> <option selected="selected" value="0">關閉</option> <!-- selected="selected" 默認選擇 --> </select>
二、js來設置選中項:修改selected屬性值
<script > var ss = document.getElementById('sel'); ss[0].selected = true;//選中 </script>
三、jquery設置選中項- 設置指定value為項中
1.設置value為vxx的項選中
$(".selector").val("vxx"); 如: $("#sel").eq(0).val("0");
四、jquery設置選中項- 設置指定text為項中
1.設置text為txx的項選中
$(".selector").find("option:contains('pxx')").attr("selected",true);
1 $(".select").eq(0).find("option:contains('關閉')").attr("selected", true); 2 var opt = $(".select").eq(0).find("option:contains('關閉')"); 3 console.log(opt); //obj {...} 4 console.log( opt.attr("selected")); // selected
selected
2.注意:
$(".selector").find("option[text='pxx']").attr("selected",true); 不可行
1 var opt = $(".select").eq(0).find("option[text='關閉']"); 2 console.log(opt); //obj{...} 3 console.log( opt.attr("selected")); //
3、注意:獲取當前選中項的value
$(".selector").val();
4、注意:獲取當前選中項的text
$(".selector").find("option:selected").text();
五、select的級聯
即第二個select(obj2)的值隨着第一個select(obj1)選中的值變化,第三個第四個等其他select(other)也跟着變化
function GetChildrenData(dataobj, obj1, obj2, other) { obj1.change(function () { var obj2Text = obj2.find("option").eq(0).text(); //請選擇... obj2.empty(); obj2.append('<option value="">' + obj2Text + '</option>'); if(other !=null ) for (var i = 0; i < other.length; i++) { var otherText = other[i].find("option").eq(0).text(); //請選擇... other[i].empty(); other[i].append('<option value="">' + otherText + '</option>'); } if ($(this).val() != "") { dataobj.GetChildredData($(this).val(), function (re) { try { var ds = JSON.parse(re.value).Table; for (var i = 0; i < ds.length; i++) { obj2.append('<option value="' + ds[i].ID + '">' + ds[i].Name + '</option>'); } } catch (e) { } }) } }) }
