jQuery Selector 是 jQuery庫中非常重要的一個組成部分。
jQuery Selector 用來選擇某個 HTML 元素,其基本語句和 CSS 的選擇器(Selector)是一樣的,所有 jQuery selector 都是以 $() 開始。
選擇某個HTML元素的方法是直接使用該元素的標(biāo)記名稱,比如選擇所有
元素
$("p")
下面的例子當(dāng)用戶點擊一個按鈕時,隱藏所有的
元素
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
jQuery #id 選擇器用來選擇定義了 id 屬性的元素,網(wǎng)頁上元素的 id 應(yīng)保證是唯一的,你可以使用 id 來選擇單個唯一的元素。
比如下面的例子,當(dāng)點擊按鈕時,只會隱藏 id 為 test 的元素。
<!DOCTYPE html>
html>
head>
script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
/script>
script>
$(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
});
/script>/head>
body>
h2>This is a heading</h2>
p>This is a paragraph.</p>
p id="test">This is another paragraph.</p>
button>Click me</button>
/body>
/html>
jQuery .class 選擇器選擇所有定義了 class 屬性為制定值的所有元素,比如下面的例子 隱藏所有類名稱為 test 的元素:
<!DOCTYPE html>
html>
head>
script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
/script>
script>
$(document).ready(function(){
$("button").click(function(){
$(".test").hide();
});
});
/script>
/head>
body>
h2 class="test">This is a heading</h2>
p class="test">This is a paragraph.</p>
p>This is another paragraph.</p>
button>Click me</button>
/body>
/html>