jquery選擇器大方向可以分為這樣:
下面我們先來看看基本選擇器總的CSS選擇器:
1.標簽選擇器:
$("element")
其中,參數element,表示待查找的HTML標記名,如$("div"),標簽選擇器獲取元素的方式是高效的,因為它繼承自javascript中的getEmelentsByTagName,它獲取的是整個元素的集合。
2.ID選擇器
$("id")
其中,參數id表示待查找的元素的id屬性值,應該在其前面加上數字符“#”,它獲取元素的方式也是高效的,因為它繼承自JavaScript中的getElementById(""),id在頁面中是唯一的,符合CSS標準。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>ID選擇器</title>
<script type="text/javascript" src="js/jquery-1.11.0.js"></script>
<script type="text/javascript">
$(function () {
alert($("#idInput").val());
});
</script>
</head>
<body>
<input type="text" value="你好,我是ID選擇器" id="idInput"/>
</body>
</html>
3.類選擇器
$("class")
其中,參數class指定應用于帶選擇器元素的類名,應在其前面加上(.)
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>class選擇器</title>
<script type="text/javascript" src="js/jquery-1.11.0.js"></script>
<script type="text/javascript">
$(function () {
$(".myClass").css("border", "2px solid blue");
});
</script>
</head>
<body>
<input type="datetime" value="" class="myClass"/>
<div class="myClass">我是DIV,哇哈哈哈</div>
</body>
</html>
4.通用選擇器
通用選擇器(*)匹配所有元素,多用于結合上下文來搜索,也就是找到HTML頁面中所有的標簽。語法格式如下:
$("*")
用通用選擇器,找到所有元素,統一設置樣式。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>通用選擇器</title>
<script type="text/javascript" src="js/jquery-1.11.0.js"></script>
<script type="text/javascript">
$(function () {
$("*").css("background-color", "green");
});
</script>
</head>
<body>
<p>窗前明月光</p>
<ul>
<li>China</li>
<li>Chinese</li>
<li>中國</li>
<li>中國人</li>
</ul>
<input type="text" value="" />
<div>
我是DIV
</div>
</body>
</html>
5.群組選擇器
群組選擇器又叫多元素選擇器,用于選擇所有指定的選擇器組合的結果,語法格式如下:
$("selector1,selector2,selector3,.....,selectorN");
其中,selector1,selector2,selector3,和selectorN均為有效的任意選擇器。根據需要,可以指定任意多個選擇器,并將匹配到的元素合并到一個結果內。
多元素選擇器,是選擇不同元素的有效方法,在返回的jquery對象中,DOM元素的順序可能有所不同,因為他們是按照文檔順序排列的。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>群組選擇器</title>
<script type="text/javascript" src="js/jquery-1.11.0.js"></script>
<script type="text/javascript">
$(function () {
$("p,ul,#myID,.myClass").css("background-color", "green");
});
</script>
</head>
<body>
<p>我是段落標簽</p>
<ul>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
</ul>
<input type="text" id="myID" value="我是文本框"/>
<span class="myClass">我是內聯元素,Span</span>
</body>
</html>
好了,先學到這,休息一下,喝口水~~~~
文章列表