Jquery中的一些技巧

来源:互联网 发布:淘宝网官方旗舰店 编辑:程序博客网 时间:2024/05/14 02:29

科技优家 2016-12-15 02:07
1.当document文档就绪时执行JavaScript代码。
我们为什么使用jQuery库呢?原因之一就在于我们可以使jQuery代码在各种不同的浏览器和存在bug的浏览器上完美运行。

 <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script> <script>     // Different ways to achieve the Document Ready event     // With jQuery     $(document).ready(function{ /* ... */});     // Short jQuery     $(function{ /* ... */});     // Without jQuery (doesn't work in older IE versions)     document.addEventListener('DOMContentLoaded',function{     // Your code goes here     });     // The Trickshot (works everywhere):     r(function{     alert('DOM Ready!');     })     function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f}</script>

2.使用route。

<script>     var route = {         _routes : {},    // 添加的路由将会被保存在这         add    : function(url, action){             this._routes[url] = action;         },         run : function() {            //pattern 相当于正则匹配             $.each(this._routes, function(pattern){                 if(location.href.match(pattern)){                    //调用run方法的时候这里将会被执行                    this();                  }             });         }     }     // 他们将会加载哪个事件呢?     route.add('index1.html', function(){         alert('你的url里面肯定有index1.html这个字符');     });     route.add('products.html', function(){         alert("你的url里面肯定有products这个字符");     });     // 只有当浏览器地址碰到url中add方法url时候参会执行adction    route.run()</script>

这里写代码片

 // You can even use regex-es: route.add('.*.html', function{ alert('This is using a regex!') }); route.run;        </script>

3.使用JavaScript中的AND技巧。
使用&&操作符的特点是如果操作符左边的表达式是false,那么它就不会再判断操作符右边的表达式了。所以:

// Instead of writing this:if($('#elem').length){    // do something}// You can write this:$('#elem').length && log("doing something");
  1. is方法比你想象的更为强大。
    下面举几个例子,我们先写一个id为elem的div。js代码如下:
// First, cache the element into a variable:var elem = $('#elem');// Is this a div?elem.is('div') && log("it's a div");// Does it have the bigbox class?elem.is('.bigbox') && log("it has the bigbox class!");// Is it visible? (we are hiding it in t`这里写代码片`his example)elem.is(':not(:visible)') && log("it is hidden!");// Animatingelem.animate({'width':200},1);// is it animated?elem.is(':animated') && log("it is animated!");

其中判断是否为动画我觉得非常不错。
5.判断你的网页一共有多少元素。
通过使用$(“*”).length;方法可以判断网页的元素数量。

// How many elements does your page have?log('This page has ' + $('*').length + ' elements!');

6.使用length属性很笨重,下面我们使用exist方法。

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

7.jQuery方法$实际上是拥有两个参数的,你知道第二个参数的作用吗?

// Select an element. The second argument is context to limit the search// You can use a selector, jQuery object or dom element$('li','#firstList').each(function{    log($(this).html);});log('-----');// Create an element. The second argument is an// object with jQuery methods to be calledvar div = $('<div>',{    "class": "bigBlue",    "css": {        "background-color":"purple"    },    "width" : 20,    "height": 20,    "animate" : {   // You can use any jQuery method as a property!        "width": 200,        "height":50    }});div.appendTo('#result');

8.使用jQuery我们可以判断一个链接是否是外部的,并来添加一个icon在非外部链接中,且确定打开方式。
这里用到了hostname属性。

<ul id="links">    <li><a href="007.html">The previous tip</a></li>    <li><a href="./009.html">The next tip</a></li>   <li><a href="http://www.google.com/">Google</a></li> </ul>// Loop through all the links$('#links a').each(function{    if(this.hostname != location.hostname){        // The link is external        $(this).append('<img src="assets/img/external.png" />').attr('target','_blank');    }});

9.jQuery中的end方法可以使你的jQuery链更加高效。

end()方法结束对当前选择的最近元素的操作,同时将选择器上移一步

html<div><li>test li<li> test div</div>jquery//首先对li隐藏然后结束li的操作并且对div进行操作$("div").find("li").hide().end().hide();

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

<script> // Prevent right clicking on this page $(function{     $(document).on("contextmenu",function(e){         e.preventDefault;     }); });</script>

11.一些站点可能会使你的网页在一个bar下面,即我们所看到在下面的网页是iframe标签中的,我们可以这样解决。

// Here is how it is used:if(window != window.top){    window.top.location = window.location;} else {    alert('This page is not displayed in a frame. Open 011.html to see it in action.');}

12.你的内联样式表并不是被设置为不可改变的,如下:

// Make the stylesheet visible and editable$('#regular-style-block').css({'display':'block', 'white-space':'pre'}) .attr('contentEditable',true);

这样即可改变内联样式了。

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

html<p class="descr">    In certain situations you might want to prevent text     on the page from being selectable. Try selecting this text and hit view     source to see how it is done.</p>js<script>    // Prevent text from being selected    $(function{        $('p.descr').attr('unselectable', 'on')        .css('user-select', 'none')        .on('selectstart', false);    });</script>

这样,内容就不能被选择啦。
14.从CDN中引入jQuery,这样的方法可以提高我们网站的性能,并且引入最新的版本也是一个不错的主意。
下面会介绍四种不同的方法。

        <!-- Case 1 - requesting jQuery from the official CDN -->        <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>        <!-- Case 2 - requesting jQuery from Google's CDN (notice the protocol) -->        <!-- <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> -->        <!-- Case 3 - requesting the latest minor 1.8.x version (only cached for an hour) -->        <!-- <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10/jquery.min.js"></script> -->        <!-- Case 4 - requesting the absolute latest jQuery version (use with caution) -->        <!-- <script src="http://code.jquery.com/jquery.min.js"></script> -->

15.保证最小的DOM操作。
我们知道js操作DOM是非常浪费资源的,我们可以看看下面的例子。

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

16.更方便的分解URL。
也许你会使用正则表达式来解析URL,但这绝对不是一种好的方法,我们可以借用a标签来实现它。

// You want to parse this address into parts:var url = 'http://tutorialzine.com/books/jquery-trickshots?trick=12#comments';// The trickshot:var a = $('<a>',{ href: url });log('Host name: ' + a.prop('hostname'));log('Path: ' + a.prop('pathname'));log('Query: ' + a.prop('search'));log('Protocol: ' + a.prop('protocol'));log('Hash: ' + a.prop('hash'));

17.不要害怕使用vanilla.js。
jQuery背负的太多,这便是原因,你可以用一般的js。

// Print the IDs of all LI items$('#colors li').each(function{    // Access the ID directly, instead    // of using jQuery's $(this).attr('id')    log(this.id);});

18.最优化你的选择器

// Let's try some benchmarks!var iterations = 10000, i;timer('Fancy');for(i=0; i < iterations; i++){    // This falls back to a SLOW JavaScript dom traversal    $('#peanutButter div:first');}timer_result('Fancy');timer('Parent-child');for(i=0; i < iterations; i++){    // Better, but still slow    $('#peanutButter div');}timer_result('Parent-child');timer('Parent-child by class');for(i=0; i < iterations; i++){    // Some browsers are a bit faster on this one    $('#peanutButter .jellyTime');

19.缓存你的selector。

// Bad:// $('#pancakes li').eq(0).remove;// $('#pancakes li').eq(1).remove;// $('#pancakes li').eq(2).remove;// Good:var pancakes = $('#pancakes li');pancakes.eq(0).remove;pancakes.eq(1).remove;pancakes.eq(2).remove;// Alternatively:// pancakes.eq(0).remove.end// .eq(1).remove.end// .eq(2).remove.end;

20.对于重复的函数只定义一次
如果你追求代码的更高性能,那么当你设置事件监听程序时必须小心,只定义一次函数然后把它的名字作为事件处理程序传递是不错的方法。

$(document).ready(function{    function showMenu{        alert('Showing menu!');        // Doing something complex here    }    $('#menuButton').click(showMenu);    $('#menuLink').click(showMenu);});

21.像对待数组一样地对待jQuery对象
由于jQuery对象有index值和长度,所以这意味着我们可以把对象当作普通的数组对待。这样也会有更好地性能。

var arr = $('li'),    iterations = 100000;timer('Native Loop');for(var z=0;z<iterations;z++){    var length = arr.length;    for(var i=0; i < length; i++){      arr[i];    }}timer_result('Native Loop');timer('jQuery Each');for(z=0;z<iterations;z++){    arr.each(function(i, val) {      this;    });}timer_result('jQuery Each');

未完待续…
本文为头条号作者发布,不代表今日头条立场
843462167@qq.com

1 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 圣空法师持五戒范戒了怎么办 美航空要是不改中国台湾标志怎么办 淘宝买的东西质量有问题怎么办 天猫618长达20天c店怎么办 新开的淘宝店铺没有生意怎么办 淘宝账号登陆限制用不了花呗怎么办 闲鱼买家签收后说是空盒怎么办 在咸鱼卖东西买家恶意退货怎么办 淘宝联系不上买家物流返回怎么办 换了支付宝绑定手机号退款怎么办啊 淘宝评价错了追评评价错了怎么办 淘宝给客户退款后还给差评怎么办 淘宝账号处于下单保护状态怎么办 淘宝卖家物流单号写错了怎么办 有个人给我发直播消息怎么办 网贷申请多了现在秒拒怎么办 顺丰快递寄的瓜果坏了怎么办 淘宝退货快递公司填错了怎么办 不小心把淘宝账号注销了怎么办 腾讯视频会员开通一个月贵怎么办 微交易买美国指数输了四千块怎么办 淘宝地址中包含了违禁词怎么办 微信支付失败但是钱扣了怎么办 支付宝向别人收款交易关闭了怎么办 从淘宝充的晋江币充值异常怎么办 接手转让店铺会员要求退卡怎么办 转转买手机卖家拒绝退款怎么办 淘宝买的东西电话号码留错了怎么办 平板电脑没电关机没保存文件怎么办 恢复出厂设置需要谷歌账号怎么办 华为手机云端里照片删除了怎么办 客户退货卖家一直没收到货怎么办 在淘宝买到假货投诉不管用怎么办 差评不接电话不回旺旺不要钱怎么办 饿了么同行恶意差评怎么办 苹果手机更新后淘宝用不了怎么办 淘宝网快递丢件了买家怎么办 评价后忘了截图五星好评怎么办 在淘宝被骗了好评返现怎么办 苹果4s微信版本过低怎么办 微信版本太低无法登录怎么办