jQuery 選擇器
jQuery選擇器是什麼?
jQuery選擇器是jQuery函式庫中非常重要的部分之一。它支援網(wǎng)頁開發(fā)者所熟知的CSS語法快速輕鬆地對頁面進(jìn)行設(shè)定。了解jQuery選擇器是開啟高效率開發(fā)jQuery之門的鑰匙。一個(gè)典型的jQuery選擇器句法形式:
$(selector).methodName();
selector是一個(gè)字串表達(dá)示,用於識別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è)元素物件將賦給變數(shù)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');
?});
其他的層級選擇器,過濾選擇器將會在以後的章節(jié)中逐步介紹。
獨(dú)立檔案中使用jQuery 函數(shù)
如果您的網(wǎng)站包含許多頁面,並且您希望您的jQuery 函數(shù)易於維護(hù),那麼請將您的jQuery 函數(shù)放到獨(dú)立的.js 檔案中。
當(dāng)我們在教程中示範(fàn) jQuery 時(shí),會將函數(shù)直接加入 <head> 部分。不過,把它們放到一個(gè)單獨(dú)的檔案中會更好,就像這樣(透過 src 屬性來引用檔案):
<head> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script> <script src="my_jquery_functions.js"></script> </head>