zoukankan      html  css  js  c++  java
  • jQuery高级技巧——DOM操作篇

     

    页面加载之DOMReady事件

    所谓domReady,也就是文档就绪,我们都知道,在操作dom时必须要在dom树加载完成后才能进行操作。如何检测DOM树已经构建完成,以下是一些实现的方式:

    1.使用jQuery:

    // with jQuery
    $(document).ready(function(){ /* ... */ });
    // shorter jQuery version
    $(function(){ /* ... */ });

    2.监听DOMContentLoaded事件,DOM 树创建完成后会触发,不支持IE10以下版本。

    // without jQuery (doesn't work in older IEs)
    document.addEventListener('DOMContentLoaded', function(){
    // your code goes here
    }, false);

    3.监听readyState状态,可实现跨浏览器

    readyState 的状态属性:

    • "uninitialized" – 原始状态
    • "loading" – 下载数据中
    • "loaded" – 下载完成
    • "interactive" – 还未执行完毕
    • "complete" – 脚本执行完毕
    r(function(){
      alert('DOM Ready!');
    });
    function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}

    这个方法是不断监听readyState的loading状态,加载完成后则执行对应方法。具体可参考:http://www.dustindiaz.com/smallest-domready-ever

    根据特定页面的执行对应的代码

    如果所有页面的代码都写在一个JavaScript文件中,这样的代码就会难以维护。简单的办法就是根据不同的页面执行不同的代码。来看下例子:

    例如在test.js有以下代码:

    var route = {
            _routes: {}, // The routes will be stored here
            add: function(url, callback) {
                this._routes[url] = callback;
            },
            run: function() {
                jQuery.each(this._routes, function(pattern) { // pattern 指向_routes对象集合的key,即url
                    if (location.href.match(pattern)) {
                        // "this" points to the function to be executed
                        this(); //this 指向指向 _routes对象集合的value,即要执行的方法
                    }
                });
            }
        }
        // Will execute only on this page:
    route.add('test.html', function() {
        alert('Hello there!');
    });
    route.add('products.html', function() {
        alert("this won't be executed :(");
    });
    // You can even use regex-es:
    route.add('.*.html', function() {
        alert('This is using a regex!');
    });
    route.run();

    使用逻辑与运算符

    利用逻辑与运算符可以简化条件分支语句写法,例子:

    一般的写法:

    // Instead of writing this:
    if($('#elem').length){
       // do something
    }

    更好的写法:

    $('#elem').length && alert("doing something");

    非常有用的jquery is()方法

    is()方法非常有用,来看些例子:

    HTML:

    <div id="elem"></div>

    JS:

    // 变量保存jQuery对象
    var elem = $('#elem');
    // 判断是否为div
    elem.is('div') && console.log("it's a div");
    // 是否包含类名.bigbox
    elem.is('.bigbox') && console.log("it has the bigbox class!");
    // 是否可见
    elem.is(':not(:visible)') && console.log("it is hidden!");
    // 设置元素执行动画
    elem.animate({'width':200},1);
    // 是否执行动画
    elem.is(':animated') && console.log("it is animated!");

    定义一个exists函数

    判断一个jQuery对象是否存在需要判断length属性,可以封装为exists函数,简化代码,更加易读。

    HTML:

    <div id="elem"></div>

    JS:

    //一般方法
    console.log($('#elem').length == 1 ? "exists!" : "doesn't exist!");
    // 封装方法
    jQuery.fn.exists = function(){ return this.length > 0; }
    console.log($('#elem').exists() ? "exists!" : "doesn't exist!");

    使用$()函数的第二个参数

    $()函数可以接收两个参数,第二个参数的作用是什么,可以来看下例子:

    <ul id="firstList" >
          <li>one</li>
          <li>two</li>
          <li>three</li>
    </ul>
    
    <ul id="secondList" >
          <li>blue</li>
          <li>green</li>
    </ul>

    作用一:

    //选取一个元素,通过#firstList限制元素只能在当前的ul节点范围内选取
    $('li' , '#firstList' ). each(function(){
        console.log($(this). html());
    });
    //相当于$('#firstList' ). find('li' );

    作用二:

    //创建一个元素。第二个参数为对应的配置属性,包含jQuery方法会被执行
    var div = $('<div>' ,{
     "class" : "bigBlue" ,
     "css" : {
     "background-color" : "purple"
     },
     "width" : 20,
     "height" : 20,
     "animate" : { //使用jQuery的方法作为属性
     "width" : 200,
     "height" : 50
     }
    });
    
    div. appendTo('body' );

    取消右键Click事件

    $(function(){
        $(document).on("contextmenu" , function(e){
                 e. preventDefault();
        });
    });

    取消文本选中

    //适应于所有浏览器
    $('p.descr' ). attr('unselectable' , 'on' ) . css('user-select' , 'none' ) . on('selectstart' , false);

    解析锚元素URL

    // 需要解析的URL
    var url = 'http://tutorialzine.com/books/jquery-trickshots?trick=12#comments' ;
    
    // 通过url创建一个新的链接
    var a = $('<a>' ,{ href:  url });
    
    console. log('Host name: ' + a. prop('hostname' ));
    console. log('Path: ' + a. prop('pathname' ));
    console. log('Query: ' + a. prop('search' ));
    console. log('Protocol: ' + a. prop('protocol' ));
    console. log('Hash: ' + a. prop('hash' ));

    输出结果:

    Host name: tutorialzine.com
    Path: /books/jquery-trickshots
    Query: ?trick=12
    Protocol: http:
    Hash: #comments

    以上是一些知识总结,如有任何建议或疑问,欢迎留言讨论。

    参考链接:

    http://www.cnblogs.com/rubylouvre/p/4277408.html

    http://www.dustindiaz.com/smallest-domready-ever

  • 相关阅读:
    IIS的各种身份验证详细测试
    HTTP Error 401.3 Unauthorized Error While creating IIS 7.0 web site on Windows 7
    C/S and B/S
    WCF ContractFilter mismatch at the EndpointDispatcher exception
    Configure WCF
    Inheritance VS Composition
    Unhandled Error in Silverlight Application, code 2103 when changing the namespace
    Java RMI VS TCP Socket
    Principles Of Object Oriented Design
    Socket处理发送和接收数据包,一个小实例:
  • 原文地址:https://www.cnblogs.com/GeniusLyzh/p/4737042.html
Copyright © 2011-2022 走看看