本篇介紹 jQuery 的內容過濾選擇器,包括:contains、:empty、:has 與:parent,並附範例說明。
<!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 src="js/jquery-1.3.2.js"></script>
<script type="text/javascript"><!--
$(function(){
$("#aContains").click(function(){ $("div:contains('hello')").each(function(){ $(this).css("background","red"); }) })
$("#aEmpty").click(function(){ $("div:empty").each(function(){ $(this).html("EmptyDIV"); }) })
$("#aHas").click(function(){ $("div:has(p)").each(function(){ $(this).css("background","red"); }) })
$("#aParent").click(function(){ $("div:parent").each(function(){ $(this).css("background","red"); }) })
})
// --></script>
</head>
<body>
<div id ="div1">
<p>hello word!</p>
</div>
<div id ="div2">
hello
</div>
<div id ="div3" height="20px">
</div>
<div id ="div4"></div>
<a href="#" id="aContains">設置內容包含"hello"的節點紅色背景顏色</a>
<a href="#" id="aEmpty">設置無內容的 DIV 內容設為 EmptyDIV</a>
<a href="#" id="aHas">設置包含 p 節點的 div 節點紅色背景顏色</a>
<a href="#" id="aParent">設置包含子節點的 div 節點紅色背景顏色</a>
</body>
</html>
element.css("attributeName","value")
用於設定 element 的 style,例如 $(this).css("background","red") 就是把節點的 background 設為 red。
1. $("TagName:contains('keyword')")
取得所有 TagName 節點中,內容包含 keyword 的節點集合。
返回值:Array(Element)。
2. $("TagName:empty")
取得所有 TagName 節點中,內容為空的節點集合。
返回值:Array(Element)。
3. $("TagName1:has(TagName2)")
取得所有 TagName1 節點中,包含 TagName2 子節點的節點集合。
返回值:Array(Element)。
4. $("TagName:parent")
取得所有 TagName 節點中,含有子節點的節點集合。
返回值:Array(Element)。