zoukankan      html  css  js  c++  java
  • jQuery中的一些小技巧

    JQ使用过程中,一些小技巧:

    1.is()方法

    根据选择器、元素或 jQuery 对象来检测匹配元素集合,如果这些元素中至少有一个元素匹配给定的参数,则返回 true。一些小应用如下:

    <ul>
      <li>list <strong>item 1</strong></li>
      <li><span>list item 2</span></li>
      <li>list item 3</li>
    </ul>
    $("ul").click(function(event) {
      var $target = $(event.target);
      if ( $target.is("li") ) {
        $target.css("background-color", "red");
      }
    });

    如此,便可以限制住,只有列表项li本身点击之后,才会触发写入的点击事件.

    其也可以做以下一些判断:

    // 是不是一个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!");

    这里有一点需要注意,&&运算符可以用来做一个判断,当前面的条件满足时,后面的会执行,但是后面的条件不能是表达式,只能是console.log()或则++i一类的.

    还有以下比较有用的用法:

    elem.animate({'width':200},1000);
    
    // 是否正在动画
    elem.is(':animated') && console.log("it is animated!");

    2.jquery中拓展方法

    $.fn是指jquery的命名空间,加上fn上的方法及属性,会对jquery实例每一个有效。
    如扩展$.fn.abc(),即$.fn.abc()是对jquery扩展了一个abc方法,那么后面你的每一个jquery实例都可以引用这个方法了.
    那么你可以这样子:$("#div").abc();
    jQuery.extend(object);为扩展jQuery类本身.为类添加新的方法。
    jQuery.fn.extend(object);给jQuery对象添加方法。

    jQuery.extend(object); 为jQuery类添加添加类方法,可以理解为添加静态方法。如:

    $.extend({ 
      add:function(a,b){returna+b;} 
    }); 

    便为 jQuery 添加一个为add 的 “静态方法”,之后便可以在引入 jQuery 的地方,使用这个方法了,
    $.add(3,4); //return 7

    jQuery.fn.exists = function(){ return this.length > 0; }
    
    console.log($('#elem').exists() ? "exists!" : "doesn't exist!");

    3.jQuery方法$()实际上是拥有两个参数的

    $('li','#firstList').each(function(){
        console.log($(this).html());
    });

    这里,第二个参数用来限制第一个参数给定的查找结果

    $('<div>',{
        "class": "bigBlue",
        "css": {
            "background-color":"purple"
        },
        "width" : 20,
        "height": 20,
        "animate" : {   // 可以设置div的动画效果
            "width": 200,
            "height":50
        }
    }).appendTo('#result');

    这里,第二个参数用来对创建的元素进行设置.

    4.jquery中的end()方法,可以让链式语法写起来更加高效,快捷.

    <ul id="meals"> <li> <ul class="breakfast"> <li class="eggs">No</li> <li class="toast">No</li> <li class="juice">No</li> </ul> </li> </ul>
    breakfast.find('.eggs').text('Yes').end() // back to breakfast
    .find('.toast').text('Yes').end().find('.juice').toggleClass('juice coffee').text('Yes');

    这里,end()会返回查找元素的上一级.

    5.contextmenu事件  右键点击

    也许希望web 应用感觉更像原生的,那么可以阻止contextmenu默认事件。

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

    当然,应用此事件,也可以自定义,右键出来的操作菜单,类似于

    6.有时候不希望网页的某一部分内容被选择比如复制粘贴这种事情,我们可以这么做:

    $('p.descr').attr('unselectable', 'on').css('user-select', 'none').on('selectstart', false);

    这样,内容就不能再被选择了.

    7.最小的DOM操作

    用js操作DOM是非常浪费资源的,下面的方法一般是我们通常的做法:

    var elem = $('#elem');
    for(var i = 0; i < 100; i++){
        elem.append('<li>element '+i+'</li>');
    }

    这样做,重复的向元素中添加,无疑是一种极大的资源浪费,而通过下面的方法,则可以减少大量的DOM操作

    var elem = $('#elem'),
    arr = []; for(var i = 0; i < 100; i++){ arr.push('<li>element '+i+'</li>'); } elem.append(arr.join(''));

    8.更方便的分解URL

    我们一般可以使用正则表达式来分解URL,但是这并不是一个好方法,我们可以借助a标签来完成URL的分解

    var url = 'http://tutorialzine.com/books/jquery-trickshots?trick=12&&abc=123#comments';
        var a = $('<a>',{ href: url });
        console.log(url);  
        console.log('Host name: ' + a.prop('hostname'));  //Host name: tutorialzine.com
        console.log('Path: ' + a.prop('pathname'));  //Path: /books/jquery-trickshots
        console.log('Query: ' + a.prop('search'));  //Query: ?trick=12&&abc=123
        console.log('Protocol: ' + a.prop('protocol'));  //Protocol: http:
        console.log('Hash: ' + a.prop('hash'));  //Hash: #comments

    这样我们就可以很快速的完成URL的分解

    9.有时候,缓存selector,反而可以优化你的js

    下面有三种情况,第一种情况是一部分人的通常做法,这种写法费力而且不讨好,后面两种方案则是对第一种的优化,可以二选一.

    第一种:

    $('#pancakes li').eq(0).remove();
    $('#pancakes li').eq(1).remove();
    $('#pancakes li').eq(2).remove();

    第二种和第三种,可以二选一:

    //第二种
    var
    pancakes = $('#pancakes li'); pancakes.eq(0).remove(); pancakes.eq(1).remove(); pancakes.eq(2).remove();
    //第三种 pancakes.eq(
    0).remove().end().eq(1).remove().end().eq(2).remove().end();

    10.on()方法

    on() 方法在被选元素及子元素上添加一个或多个事件处理程序。

    自 jQuery 版本 1.7 起,on() 方法是 bind()、live() 和 delegate() 方法的新的替代品。该方法给 API 带来很多便利,推荐使用该方法,它简化了 jQuery 代码库。

    注意:使用 on() 方法添加的事件处理程序适用于当前及未来的元素(比如由脚本创建的新元素)。

    提示:如需移除事件处理程序,请使用 off() 方法。

    提示:如需添加只运行一次的事件然后移除,请使用 one 方法。

    $(selector).on(event,childSelector,data,function,map)

    11.模拟触发事件

    我们可以通过trigger模拟触发一个click事件

    var press = $('#press');
    press.on('click',function(e, how){
        how = how || '';
        alert('The buton was clicked ' + how + '!');
    });
    
    press.trigger('click');
    press.trigger('click',['fast']);

    同时,我们亦可以,使用on()方法创建自己喜欢的事件名称,然后通过trigger来触发。举例如下:

    <button id="button1">Jump</button> <button id="button2">Punch</button> <button id="button3">Click</button> <button id="clear" style="float: right;">Clear</button> <div id="eventDiv"></div>
    var button1 = $('#button1'),
        button2 = $('#button2'),
        button3 = $('#button3'),
        clear = $('#clear'),
        div = $('#eventDiv');
    
    div.on({
        jump : function(){
            alert('Jumped!');
        },
    
        punch : function(e,data){
            alert('Punched '+data+'!');
        },
    
        click : function(){
            alert('Simulated click!');
        }
    
    });
    
    button1.click(function(){
        div.trigger('jump');
    });
    
    button2.click(function(){
        // Pass data along with the event
        div.trigger('punch',['hard']);
    });
    
    button3.click(function(){
        div.trigger('click');
    });
    
    clear.click(function(){
        //some clear code
    });

    12.触摸事件

    // Define some variables
    var ball = $('<div id="ball"></div>').appendTo('body'),
    startPosition = {}, elementPosition = {};
    
    // Listen for mouse and touch events
    ball.on('mousedown touchstart',function(e){
        e.preventDefault();
    
        // Normalizing the touch event object
        e = (e.originalEvent.touches) ? e.originalEvent.touches[0] : e;
    
        // Recording current positions
        startPosition = {x: e.pageX, y: e.pageY};
        elementPosition = {x: ball.offset().left, y: ball.offset().top};
    
        // These event listeners will be removed later
        ball.on('mousemove.rem touchmove.rem',function(e){
            e = (e.originalEvent.touches) ? e.originalEvent.touches[0] : e;
    
            ball.css({
                top:elementPosition.y + (e.pageY - startPosition.y),
                left: elementPosition.x + (e.pageX - startPosition.x),
            });
    
        });
    });
    
    ball.on('mouseup touchend',function(){
        // Removing the heavy *move listeners
        ball.off('.rem');
    });

    13.更快的阻止默认事件

    通常,我们用event.preventDefalut()来阻止默认事件,但是jquery为此提供了更简便的方法:

    <a href="http://google.com/" id="goToGoogle">Go To Google</a>
    $('#goToGoogle').click(false);

    14.使用event.result链接多个事件处理程序。

    对一个元素绑定多个事件处理程序并不常见,而使用event.result更可以将多个事件处理程序联系起来。看下面的例子。

    var press = $('#press');
    press.on('click',function(){
        return 'Hip';
    });
    
    press.on('click',function(e){
        console.log(e.result + ' Hop!');
    })
    //控制台输出: HipHop!

    15.平行的运行多个Ajax请求

    当我们需要发送多个Ajax请求是,相反于等待一个发送结束再发送下一个,我们可以平行地发送来加速Ajax请求发送。

    $.when($.get('assets/misc/1.json'), $.get('assets/misc/2.json')).then(function(r1, r2){
        console.log(r1[0].message + " " + r2[0].message);
    })

    16.通过jQuery获得ip

    我们不仅可以在电脑上ping到一个网站的ip,也可以通过jQuery得到

    $.get('https://jsonip.com/', function(res){ console.log(res.ip); });

    17.使用最简单的ajax请求

    jQuery(使用ajax)提供了一个速记的方法来快速下载内容并添加在一个元素中。

    <p class="content"></p> <p class="content"></p>
    var contentDivs = $('.content');
    contentDivs.eq(0).load('1.txt');
    contentDivs.eq(1).load('1.html #header');

    18.通过IP地址获得地理位置

    有很多在线服务可以告诉我们IP地址所在的城市和国家,下面我们先ping到百度的IP地址,然后获取其地理位置:

    var ip = '119.75.218.70',
        api  = 'http://freegeoip.net/json/' + ip + '?callback=?';
    
    
    $.getJSON(api, function(r){
    
        console.log('How is the weather in ' + r.city + ', ' + r.country_name + '?');
    
    });

    19.使用匿名函数来产生一个独立的代码块

    定义全局变量和函数是一种代码很粗糙的行为,更好的方式是通过使用匿名函数使你的代码独立于块之中。看下面的例子:

    (function($){
        var c = 1;
        $.fn.count = function(){
            log(c++);
            return this;
        };  
    })(jQuery); 
    
    $(document).count();
    $('body').count().count();

    暂无...

  • 相关阅读:
    Lync二次开发
    Socket 一对多通信
    DBImport V3.1 数据互导工具及文档生成器更新发布
    Sql学习第六天——SQL 巩固练习(用到了前几天几个知识点)
    文件监控
    Google Protocol Buffers 入门
    [原]常用Linux命令总结[Thx for commandlinefu]
    清理SQL Server日志释放文件空间
    ASP.NET MVC动态二级域名及ASP.NET管道机制
    搜索引擎——JobSearch简介
  • 原文地址:https://www.cnblogs.com/fbzs/p/6296145.html
Copyright © 2011-2022 走看看