博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
jQuery Selector
阅读量:7002 次
发布时间:2019-06-27

本文共 1674 字,大约阅读时间需要 5 分钟。

hot3.png

jQuery Selector 是jQuery库中非常重要的一个组成部分。

jQuery Selector 用来选择某个HTML元素,其基本语句和CSS的选择器(Selector)是一样的,所有jQuery selector 都是以$()开始。

anchor.gif选择HTML标记

选择某个HTML元素的方法是直接使用该元素的标记名称,比如选择所有<p>元素

  1. $("p")  
  2.    

下面的例子当用户点击一个按钮时,隐藏所有的<p>元素

  1. $(document).ready(function(){  
  2.    $("button").click(function(){  
  3.      $("p").hide();  
  4.    });  
  5.  });  
  6.    

anchor.gif#id 选择

jQuery #id 选择器用来选择定义了id 属性的元素,网页上元素的id应保证是唯一的,你可以使用id来选择单个唯一的元素。

比如下面的例子,当点击按钮时,只会隐藏id为test 的元素。

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4. <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">  
  5. </script>  
  6. <script>  
  7. $(document).ready(function(){  
  8.   $("button").click(function(){  
  9.     $("#test").hide();  
  10.   });  
  11. });  
  12. </script>  
  13. </head>  
  14.   
  15. <body>  
  16. <h2>This is a heading</h2>  
  17. <p>This is a paragraph.</p>  
  18. <p id="test">This is another paragraph.</p>  
  19. <button>Click me</button>  
  20. </body>  
  21.   
  22. </html>  
  23.   
  24.    

anchor.gif.class 选择器

jQuery .class 选择器选择所有定义了class属性为制定值的所有元素,比如下面的例子 隐藏所有类名称为test的元素:

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4. <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">  
  5. </script>  
  6. <script>  
  7. $(document).ready(function(){  
  8.   $("button").click(function(){  
  9.     $(".test").hide();  
  10.   });  
  11. });  
  12. </script>  
  13. </head>  
  14. <body>  
  15.   
  16. <h2 class="test">This is a heading</h2>  
  17. <p class="test">This is a paragraph.</p>  
  18. <p>This is another paragraph.</p>  
  19. <button>Click me</button>  
  20. </body>  
  21. </html>  
  22.    

anchor.gif更多的例子

语法 说明
$(“*”) 选择所以元素
$(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>元素

转载于:https://my.oschina.net/u/990986/blog/112037

你可能感兴趣的文章