jQuery Selector 是jQuery库中很是重要的一个组成部分。 html
jQuery Selector 用来选择某个HTML元素,其基本语句和CSS的选择器(Selector)是同样的,全部jQuery selector 都是以$()开始。 jquery
选择HTML标记
选择某个HTML元素的方法是直接使用该元素的标记名称,好比选择全部<p>元素 ajax
下面的例子当用户点击一个按钮时,隐藏全部的<p>元素 api
- $(document).ready(function(){
- $("button").click(function(){
- $("p").hide();
- });
- });
-
#id 选择
jQuery #id 选择器用来选择定义了id 属性的元素,网页上元素的id应保证是惟一的,你能够使用id来选择单个惟一的元素。 ide
好比下面的例子,当点击按钮时,只会隐藏id为test 的元素。 this
- <!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的元素: google
- <!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元素 |
$(“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>元素 |