jQuery 選擇器
jQuery選擇器是什么?
jQuery選擇器是jQuery庫中非常重要的部分之一。它支持網(wǎng)頁開發(fā)者所熟知的CSS語法快速輕松地對頁面進(jìn)行設(shè)置。了解jQuery選擇器是打開高效開發(fā)jQuery之門的鑰匙。一個(gè)典型的jQuery選擇器句法形式:
$(selector).methodName();
selector是一個(gè)字符串表達(dá)示,用于識(shí)別DOM中的元素,然后使用jQuery提供的方法集合加以設(shè)置。
大多數(shù)情況下jQuery支持這樣的操作:
$(selector).method1().method2().method3();
這個(gè)實(shí)例表示隱含DOM中id=”goAway”的元素,然后為其添加一個(gè)class=”incognito”屬性。
$('#goAway').hide().addClass('incognito');
提示一下:當(dāng)選擇器表達(dá)示匹配多個(gè)元素時(shí),可以象JavaScritp數(shù)組操作一樣,方便靈活地利用數(shù)組指針進(jìn)行選取。這是例子:
var element = $('img')[0];
匹配表達(dá)示的元素中,第一個(gè)元素對象將賦給變量element。
基本選擇器
1.元素選擇器
jQuery 元素選擇器基于元素名選取元素。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</title> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ $("p").hide(); }); }); </script> </head> <body> <h2>標(biāo)題</h2> <p>段落。</p> <p>另一個(gè)段落。</p> <button>點(diǎn)擊隱藏P標(biāo)簽內(nèi)容</button> </body> </html>
2.?#id 選擇器
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</title> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ $("#test").hide(); }); }); </script> </head> <body> <p>段落</p> <p id="test">另一個(gè)段落</p> <button>點(diǎn)擊隱藏id</button> </body> </html>
3.class選擇器
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</title> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ $(".test").hide(); }); }); </script> </head> <body> <h2 class="test">標(biāo)題</h2> <p class="test">段落。</p> <button>點(diǎn)擊隱藏所有class</button> </body> </html>
4.element選擇器
將p元素的文字大小設(shè)置為12px:
$(document).ready(function () {
??????? $('p').css('font-size', '12px');
??? });
5.?* 選擇器
$(document).ready(function () {
??????? // 遍歷form下的所有元素,將字體顏色設(shè)置為紅色
??????? $('form *').css('color', '#FF0000');
??? });
6. 并列選擇器
$(document).ready(function () {
? ?// 將p元素和div元素的margin設(shè)為0
? ?$('p, div').css('margin', '0');
?});
其他的層級選擇器,過濾選擇器將會(huì)在以后的章節(jié)中逐步介紹。
獨(dú)立文件中使用 jQuery 函數(shù)
如果您的網(wǎng)站包含許多頁面,并且您希望您的 jQuery 函數(shù)易于維護(hù),那么請把您的 jQuery 函數(shù)放到獨(dú)立的 .js 文件中。
當(dāng)我們在教程中演示 jQuery 時(shí),會(huì)將函數(shù)直接添加到 <head> 部分中。不過,把它們放到一個(gè)單獨(dú)的文件中會(huì)更好,就像這樣(通過 src 屬性來引用文件):
<head> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script> <script src="my_jquery_functions.js"></script> </head>