表單中包含了形形色色的表單域,而「表單域屬性過濾器」能幫助我們精準地取得已選中的單選按鈕、複選框與列表項,也能依據是否可用來查找表單域。本文將介紹 :checked、:enabled、:disabled、:selected 等常用過濾器,並附上完整實例。
$(selector:checked):選取所有被選中的表單域,可用於 radio 與 checkbox。$(selector:enabled):選取所有可用的表單域。$(selector:disabled):選取所有被停用的表單域。$(selector:selected):從列表框中選取所有被選中的 option 元素。$(selector:hidden):選取所有不可見元素。$(selector:visible):選取所有可見元素。<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>表單域屬性過濾選擇器應用示例</title>
<script type="text/javascript" src="jquery-1.7.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("input:checked").css("border", "1px solid red");
$("input:disabled").css("background", "#FCF");
$("input:enabled").val("可用文字框");
});
</script>
</head>
<body>
<h3 align="center">表單域屬性過濾選擇器應用示例</h3>
<table width="602" height="81" border="1">
<tr>
<td>複選框:</td>
<td>
<input type="checkbox" checked="checked" />被選中的複選框
<input type="checkbox" checked="checked" />被選中的複選框
<input type="checkbox" />沒有被選中的複選框
</td>
</tr>
<tr>
<td>可用文字框:</td><td><input type="text"/></td>
</tr>
<tr>
<td>不可用文字框:</td><td><input type="text" disabled="disabled" /></td>
</tr>
<tr>
<td>下拉列表</td>
<td>
<select name="test">
<option>浙江</option>
<option>湖南</option>
<option selected="selected">北京</option>
<option selected="selected">天津</option>
</select>
</td>
</tr>
</table>
</body>
</html>
效果圖:

這些屬性過濾器讓表單操作變得直觀而靈活,無論是取得使用者勾選的項目,還是批次處理啟停狀態,都能輕鬆完成。希望本文能對你的 jQuery 程式設計有所幫助。