参考
介绍
简单示例
使用
指定元素
常用 api
addClass
示例
选择父级元素

参考

介绍

jQuery 是一组便捷的 JavaScript API。

简单示例

你可以下载 jquery 到本地, http://code.jquery.com/jquery-1.4.2.min.js , 保存下面文本为 1.html 。用浏览器打开即可。

<html>
<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {
      alert("Hello.world!");
      });
    </script>
</head>
<body>
<h1>加载页面就弹出"Hello.world!"窗口。</p>
</body>
</html>

注释: head 部分第一行指定 jquery-1.4.2 的路径,如果懒得下载也可以指定 url 地址。

<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>

使用

指定元素

看一段示例代码:

$(document).ready(function() {
	$("a").click(function() {
		alert("Hello world!");
	});
});

$("a") 是一个jQuery选择器(selector),在这里,它选择所有的a标签(译者 Keel注:即<a></a>),$号是 jQuery “类”(jQuery "class")的一个别称,因此 $()构造了一个新的jQuery 对象(jQuery object)。函数 click() 是这个jQuery 对象的一个方法,它绑定了一个单击事件到所有选中的标签(这里是所有的a标 签),并在事件触发时执行了它所提供的alert方法.

因此此段jQuery的代码与下面直接的 JavaScript 代码相似:

<a href="" onclick="alert('Hello world')">Link</a>

不同之处很明显,用jQuery不需要在每个a标签上写onclick事件,所以我们拥有了 一个整洁的结构文档(HTML)和一个行为文档(JS),达到了将结构与行为分开的目 的,就像我们使用CSS追求的一样.

常用 api

addClass

这个api在指定的元素上添加 class (CSS 的属性),下面在 id 为 "#title" 的元素上添加 'red' 属性,red属性在head部分定义为背景为红色:

<html>
<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

    <style type="text/css">
      h1 { text-align: center; }
      .red { background-color: red;}
    </style>

    <script type="text/javascript">
      $(document).ready(function() {
        $('#title').addClass('red');
      });
    </script>

</head>
<body>
<h1 id='title'>红色吗?</h1>
<p>上面的 title 会是红色!</p>
</body>
</html>

示例

选择父级元素

除了选择同级别的元素外,你也可以选择父级的元素。可能你想在用户鼠标移到 文章某段的某个链接时,它的父级元素—也就是文章的这一段突出显示:

$(document).ready(function() {
  $("a").hover(function() {
    $(this).parents("p").addClass("red");
    }, function() {
    $(this).parents("p").removeClass("red");
  });
});