ITeye博客

jQuery:基本教程

longsy · 2009-09-30 15:24 · 编程所学 · Markdown

jQuery:基本教程

这个教程是帮助初始学习jQuery的人.

<html>

  <head>

    <script type="text/javascript" src="jquery.js"></script>

    <script type="text/javascript">

    </script>

  </head>

  <body>

    <a href="http://jquery.com/">jQuery</a>

  </body>

</html>

编辑<script>的src属性值,使其指向jquery.js文件.例如,如果jquery.js文件与HTML文件所有目录相同,则可写成:

 <script type="text/javascript" src="jquery.js"></script>

可以从 Downloading jQuery 下载jquery.js.

在document准备加载时运行指定代码

许多javscript程序员都采取出下的方式:

 window.onload = function(){ alert("welcome"); }

然而,使用这种方式,要想运行代码首先必须等待document加载完毕.如果页面中包含了许多图片,且页面没有加载完毕,则要想立即运行的代码将无法运行

为了避免以上问题,jQuery采用了一种语句,检测document并等待其为操作做好准备.这就是所谓的ready event

 $(document).ready(function(){

   // Your code here

 });

在ready event中,添加了一个点击链接的处理函数:

 $(document).ready(function(){

   $("a").click(function(event){

     alert("Thanks for visiting!");

   });

 });

保存你的HTML文件,重新加载页面,点击页面上的链接,你将会在页面跳转之前得到一个弹出信息提示框

如果想阻止点击事件所触发的默认行为--跳转到其他页面,可以调动event.preventDefault() :

 $(document).ready(function(){

   $("a").click(function(event){

     alert("As you can see, the link no longer took you to jquery.com");

     event.preventDefault();

   });

 });

完整的实例

以下是完整一个HTML文件.注意jquery.js文件引用于Google网络链接

 <!DOCTYPE html>

 <html lang="en">

 <head>

   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>

   <script type="text/javascript">

     $(document).ready(function(){

       $("a").click(function(event){

         alert("As you can see, the link no longer took you to jquery.com");

         event.preventDefault();

       });

     });

     

   </script>

 </head>

 <body>

   <a href="http://jquery.com/">jQuery</a>

 </body>

 </html>

添加和移除CSS class

在head标签中添加一些CSS样式

 <style type="text/css">

    a.test { font-weight: bold; }

 </style>

通过jquery的addClass函数来添加CSS class

  $("a").addClass("test");

现在你所有的a元素都将会加粗.

通过jquery的removeClass函数来移除CSS class

 $("a").removeClass("test");

CSS允许为一个元素添加多个class

 

特效

在jQuery中,有几个生成特效的函数被提供用于使网页变的更具吸引:

 $("a").click(function(event){

   event.preventDefault();

   $(this).hide("slow");

 });

现在,你点击任何一个链接,该链接会慢慢地消失(隐藏) 

回调与函数

回调是一种作为其它函数的参数.当主函数执行完成后,回调函数开始执行.

还有一种重要的事情就是回调函数作为参数时是如何正确传递的.

不带参数的回调函数

如下:

 $.get('myhtmlpage.html', myCallBack);

注意 第二个参数是回调函数名(不是字符串,也没有括号). 

带参数的回调函数

错误

这是一种错误的方式

 $.get('myhtmlpage.html', myCallBack(param1, param2));

这将无法工作,因为它调用了

myCallBack(param1, param2)

并且它将返回值作为$.get()第二个参数. 

正确

创建匿名函数作为回调函数,并调用带参的myCallBack

$.get('myhtmlpage.html', function(){

  myCallBack(param1, param2);

});

当$.get执行完后,两个参数将会被赋值

<!--EndFragment-->

评论(2)

  1. #2 楼 · 新入职 · 2010-07-20 10:03

    咦?竟然在2个月前留过言!

  2. #1 楼 · jiangnan9399 · 2010-05-12 09:34

    我现在正在学习JQery看了你的教程帮助很大,谢谢啦, :idea:

评论功能维护中,当前仅展示历史评论。