比如 <select id="testSelect"></select>
- 設(shè)置 value 為 test 的項選中
$("#testSelect").val("test");
- 設(shè)置 text 為 test 的項選中
$("#testSelect").find("option[text='test']").attr("selected", true);
example 1
<html>
<head>
<script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script>
<script>
function sel() {
document.getElementById("show_index").innerHTML = $("#testSelect").get(0).selectedIndex;
document.getElementById("show_all_text").innerHTML = $("#testSelect").text(); // 獲取所有的文本
document.getElementById("show_text").innerHTML = $("#testSelect option:selected").text(); // 獲取選中的選項的文本
document.getElementById("show_value").innerHTML = $("#testSelect").val();
if ($("#op_3").is(":checked")) {
document.getElementById("show_isSelected").innerHTML = "選中了";
} else {
document.getElementById("show_isSelected").innerHTML = "沒選中";
}
$("#testSelect").aped("<option value="+op_5+">"+推薦系統(tǒng)+"<option>");
}
function set() {
$("#testSelect").val(""); //設(shè)置value為空的項為選中狀態(tài)
sel();
}
</script>
</head>
<body>
<button onclick="set()">測試</button>
<select id="testSelect" onchange="sel()">
<option id="op_0" value="">請選擇</option>
<option id="op_1" value="Deep Learning">深度學習</option>
<option id="op_2" value="Machine Learning">機器學習</option>
<option id="op_3" value="Data Mining">數(shù)據(jù)挖掘</option>
<option id="op_4" value="Image Processing">圖像處理</option>
</select>
<br>
<hr><font color="red">選中的option索引:</font><p id="show_index"></p>
<hr><font color="red">選中的option文本:</font><p id="show_text"></p>
<hr><font color="red">選中的option的值:</font><p id="show_value"></p>
<hr><font color="red">“數(shù)據(jù)挖掘”選項是否被選中:</font><p id="show_isSelected"></p>
<hr><font color="red">所有選項的文本:</font><p id="show_all_text"></p>
</body>
</html>
附
該文章于2017年9月4日于CSDN上首次發(fā)表笆呆,2017年12月24日搬家至此!