jquery - 选择器

来源:互联网 发布:tftp软件 编辑:程序博客网 时间:2024/06/06 10:53

1、从该网址上下载最新的jquery.js插件,http://jquery.com/,如图所示:

 

2、导入插件

<html>

<head>
     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
     <title>无标题文档</title>
</head>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript">
 $(document).ready(function(){
    $("p.test").click(function(){
   $(this).hide();
   });
 });
</script>

<body>
  <p class="test"> click me !

</body>
</html>

 

3、jquery 基本语法:

  1)jquery元素选择器:

jQuery 使用 CSS 选择器来选取 HTML 元素。

$("p") 选取 <p> 元素。

$("p.intro") 选取所有 class="intro" 的 <p> 元素。

$("p#demo") 选取 id="demo" 的第一个 <p> 元素。

 

  2) jquery属性选择器:

$(" [href] ")选取所有带有href属性的元素 

$("[href='#']") 选取所有带有 href 值等于 "#" 的元素。

$("[href!='#']") 选取所有带有 href 值不等于 "#" 的元素。

$("[href$='.jpg']") 选取所有 href 值以 ".jpg" 结尾的元素。

 

jQuery CSS 选择器

jQuery CSS 选择器可用于改变 HTML 元素的 CSS 属性。

下面的例子把所有 p 元素的背景颜色更改为红色:

$("p").css("background-color","red");

 

更多选择器实例:

$(" ul li:first ")  -- 每个<ul>的第一个<li>元素

$(" div#intro.head") -- id="intro"的<div>元素的所有class=head的元素

详解:

1> $("*") 所有元素

2>$(".intro,demo") 所有class="intro"且class="demo"的元素

3>$("p:first") 第一个<p>元素

4>$("p:last")最后一个<p> 元素

5>$("tr:even ") 所有的偶数<tr>元素

6>$("tr:odd")所有的奇数<tr>元素

7> :eq(index)

$("ul li:eq(3)")  列表中的第四个元素(index从0开始)

8> :gt(no)

$("ul li:gt(3)") 列出index>3的元素

 

9> $("ul li:lt(3)") 列出index<3的元素

10> :not(selector)

 $("p:not('.test')")  所有class不是test的p元素

$("input:not(:empty)")所有不为空的input元素  ????

11>

$(":header") 所有的标题元素 <h1> - <h6>

 

12>:animated 所有动画元素

 

13> :contains(text)

$(":contains("xxx")")

 

选择所有包含 "is" 的 <p> 元素:

$("p:contains(is)")
 

:contains 选择器选取包含指定字符串的元素。

该字符串可以是直接包含在元素中的文本,或者被包含于子元素中。

经常与其他元素/选择器一起使用,来选择指定的组中包含指定文本的元素(如上面的例子)。

 

扩展:$("ul li:contains('xxxx')").css("background-color","red");  【选择ul li 里面包含xxxx的一行】

也可以 $("ul li:contains(xxxx)").css("background-color","red");

14>

s1,s2,s3

$("th,td,.intro")

所有带有匹配选择的元素

 

15>