jQuery Selector 是jQuery庫中非常重要的一個組成部分。 jQuery Selector 用來選擇某個HTML元素,其基本語句和CSS的選取器(Selector)是一樣的,所有jQuery selector 都是以$()開始。 選擇HTML標記選擇某個HTML元素的方法是直接使用該元素的標記名稱,比如選擇所有<p>元素 [javascript] view plaincopyprint?$("p") $("p") 下面的例子當使用者點擊一個按鈕時,隱藏所有的<p>元素 [javascript] view plaincopyprint?$(document).ready(function(){ $("button").click(function(){ $("p").hide(); }); }); $(document).ready(function(){ $("button").click(function(){ $("p").hide(); }); }); #id 選擇 jQuery #id 選取器用來選擇定義了id 屬性的元素,網頁上元素的id應保證是唯一的,你可以使用id來選擇單個唯一的元素。 比如下面的例子,當點擊按鈕時,只會隱藏id為test 的元素。 [html] view plaincopyprint?<!DOCTYPE html> <html> <head> <script src="//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> <!DOCTYPE html><html><head><script src="//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> .class 選取器jQuery .class 選取器選擇所有定義了class屬性為制定值的所有元素,比如下面的例子 隱藏所有類名稱為test的元素: [html] view plaincopyprint?<!DOCTYPE html> <html> <head> <script src="//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> <!DOCTYPE html><html><head><script src="//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> 更多的例子文法 說明 $(“*”) 選擇所以元素 $(this) 選擇當前元素 $(“p.intro”) 選項所有class=intro的p元素 $(“p:first”) 選擇第一個p元素 www.2cto.com$(“ul li:first”) 選擇第一個<ul>元素的第一個<li>元素 $(“ul li:first-child”) 選擇每個<ul>的第一個 元素 $(“[href]“) 選擇所有帶href的元素 $(“a[target='_blank']“) 選擇所有target=_blank的a元素 $(“a[target!='_blank']“) 選擇所有target!=_blank的a元素 $(“:button”) 選擇所有button元素及input類型為button的元素 $(“tr:even”) 選擇所有偶數行<tr>元素 $(“tr:odd”) 選擇所有單數行<tr>元素