:contains() 的問題是它只做「包含」比對,不夠精確。搜尋 'xx' 時,內容是 'xx' 的元素和內容是 'xxabc' 的元素都會被選中。這個範例示範如何搭配 map() 做二次過濾,達到完全相等才成立的效果。
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
// 依 select 中 option 的文字來執行選中
// 以下兩種寫法都是錯的:
// $("#selectbox option[text='第二項']");
// $("#selectbox option").filter("[text='第二項']");
// 正確寫法
$("#btn4").click(function () {
var $option = $("#selectbox option:contains('第二項')").map(function () {
if ($(this).text() == "第二項") {
return this;
}
});
alert($option.length > 0 ? "有對象" : "無對象");
$option.attr("selected", true);
});
});
</script>
</head>
<body>
<form id="form1">
<div>
<select id="selectbox">
<option value="1">第一項</option>
<option value="2">第二項</option>
<option value="21">第二項1</option>
</select>
<input type="button" id="btn4" value="contains 測試" />
</div>
</form>
</body>
</html>
option 元素並沒有名為 text 的屬性,文字內容是它的 innerHTML/text 節點。寫 [text='第二項'] 是在找屬性,永遠選不到東西。這也是為什麼必須先用 :contains() 縮小範圍,再用 $(this).text() 取值比對。
這個 select 裡有「第二項」與「第二項1」兩筆,若只用 :contains('第二項'),兩筆都會被選中,選中的就會是最後一筆。加上 .map() 做精確比對後,只有文字完全等於「第二項」的那一筆會被回傳——map 的回呼沒回傳值時,該項會被排除,這正是它同時具備 filter 效果的用法。
用屬性過濾搭配 filter 函式,語意更清楚:
var $option = $("#selectbox option").filter(function () {
return $(this).text() === "第二項";
});
$option.attr("selected", true);
或者直接用 $.each 找到就跳出:
$("#selectbox option").each(function () {
if ($(this).text() === "第二項") {
$(this).prop("selected", true);
return false; // 找到即停止
}
});
最後補充兩點。第一,設定選中狀態請用 .prop('selected', true) 而不是 .attr()——selected 是元素的當前狀態而非初始屬性,這正是 attr 與 prop 最典型的差異所在。第二,如果只是要依值(而非文字)選中某個 option,根本不需要 :contains,寫 $('#selectbox').val('2') 一行就解決了。依文字比對通常意味著 value 設計得不清楚,值得回頭檢視資料結構。