jQuery笔记(五):事件

使用jQuery,可以用更少的代码,非常容易理解的语法,轻松地应用所有的原声JavaScript事件捕获来自用户键盘和鼠标的交互。这正是jQuery的风格。

1、使用.ready()事件检测DOM是否完全加载

当HTML()文档加载完成时,触发.ready()事件。因此常用.ready()检查DOM是否加载完毕。当DOM准备好之后,这个时间将触发所有包在.ready()事件处理函数中的JavaScript或jQuery代码。它并不需要等待页面的图片或视频成功加载。

一般写jQuery代码最开始就是使用.ready()事件:

$(document).ready(function(){

  //TODO...

});

查看源码,.bindReady()方法中已经跨浏览器处理了DOM是否加载完成。

View Code
bindReady: function() {
        if ( readyList ) {
            return;
        }

        readyList = jQuery.Callbacks( "once memory" );

        // Catch cases where $(document).ready() is called after the
        // browser event has already occurred.
        if ( document.readyState === "complete" ) {
            // Handle it asynchronously to allow scripts the opportunity to delay ready
            return setTimeout( jQuery.ready, 1 );
        }

        // Mozilla, Opera and webkit nightlies currently support this event
        if ( document.addEventListener ) {
            // Use the handy event callback
            document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );

            // A fallback to window.onload, that will always work
            window.addEventListener( "load", jQuery.ready, false );

        // If IE event model is used
        } else if ( document.attachEvent ) {
            // ensure firing before onload,
            // maybe late but safe also for iframes
            document.attachEvent( "onreadystatechange", DOMContentLoaded );

            // A fallback to window.onload, that will always work
            window.attachEvent( "onload", jQuery.ready );

            // If IE and not a frame
            // continually check to see if the document is ready
            var toplevel = false;

            try {
                toplevel = window.frameElement == null;
            } catch(e) {}

            if ( document.documentElement.doScroll && toplevel ) {
                doScrollCheck();
            }
        }
    }

2、使用.load()事件预加载图片

当页面上有很多图片时,如果采用了预加载技术,就可以做到当用户在页面上执行某些操作时这些图片已经准备就绪。让用户等待页面中的图片一张张加载完毕时最糟糕的用户体验之一。

例子:

<script type="text/javascript">
  
          $(document).ready(function(){

              var imgArray = ["1.jpg","2.jpg","3.jpg","4.jpg","5.jpg"];
              
              var imgArrLength = imgArray.length;
            //alert(imgArrLength);
              for(var i =0;i<imgArrLength;i++){
                $('<img/>').attr('src','../images/'+imgArray[i]).load(function(){
                    $('.gallery').append($(this));
                });
            }
              
          });
      
  </script>
  <body>
    <div class="content">
        <p>I run 4 times a week.</p>
        <p>I lift weights 3 times a week.</p>
        <div class="gallery">
        </div>
    </div>
  </body>

firebug下的html:

3、在用户离开页面时显示一条提示消息

使用.unload事件。unload事件在老式浏览器版本中不能正常工作。当用户单击浏览器关闭按钮或者在地址栏里输入新网址即将打开新页面的时候,unload事件就会发生。比如,在网站上填写一张表单,还没填写完成,用户突然放弃,这时就可以使用unload事件,显示一条提示信息,问问是否真的打算离开。

$(window).unload(function(){
                  if(confirm("你确定要离开吗?")){
                    e.preventDefault();
                }
              });

在IE9下能正常工作,但在FireFox17.0.1(最新版本)不能工作。报错了,应该是FF的问题吧。

4、使用error事件显示备用图片

当某个产品页的某张图片出现死链接,除非正好浏览到这个页面,否则无法知道这个页面有图片丢失。利用jQuery的error事件,能检测到图片丢失并未它设置一张默认图片。

例子:

<script type="text/javascript">           
          $(document).ready(function(){
            $("img").error(function(){
              $("img").replaceWith("<p><b>图片未加载!</b></p>");
            });
          });
  </script>
  <body>
    <img src="errorimg.gif" />
    <p>如果上面的图像没有正确地加载,会被替换为一段 "图片未加载" 的文本。</p>
  </body>

书写没错,但是在FF和IE9下测试不能触发.error()事件。但同样的代码,在w3school在线测试工具运行,能成功。这个有待考察啊。

posted @ 2013-03-13 21:54  爱生活者wmmang  Views(254)  Comments(0Edit  收藏  举报