jQuery使用技巧

2017年開張了,朝着自己的小目標前進。夢想一定要有,萬一實現了呢! 2天上沒有掉餡餅 擼起袖子加油幹 努力拼搏才能實現自己的夢想。

1.禁用網頁上的右鍵菜單

$(document).ready(function(){
    $(document).bind("contextmenu",function(e{
        return false;
    }));
});

2.新窗口打開頁面

$(document).ready(function(){
    $('a[href^="https://www.google.com"]').attr("target","_blank");// href的超鏈接會在新窗口打開

  <a href="https://www.google.com" rel="newwindows">newwindow</a>
$("a[rel$='newwindow']").click(function(){
        this.target="_blank";
    });
});

3.判斷瀏覽器的類型

在jQuery 1.3版本之後,官方推薦使用$.support 來代替$.browser
jQuery 1.9版本之後 刪除了$.browser, 取而代之的是 $.support 。 在更新的 2.0 版本中,將不再支持 IE 6/7/8。 如果用戶需要支持 IE 6/7/8,只能使用 jQuery 1.9。 如果要全面支持 IE,並混合使用 jQuery 1.9 和 2.0, 官方的解決方案是:

<!--[if lt IE 9]>
    <script src='jquery-1.9.0.js'></script>
<![endif]-->
<!--[if gte IE 9]>
    <script src='jquery-2.0.0.js'></script>
<![endif]-->

jQuery 1.9版本之前判斷瀏覽器的方法如下

$(document).ready(function(){
    var $browser=$.browser;
    //Firefox 1.8+
    if($browser.mozilla&&$browser.version>='1.8'){}
    //Safari
    if($browser.safari){}
    //Chrome
    if($browser.chrome){}  //我用谷歌瀏覽器 x64 Chrome: 56.0.2924.3 這個版本測試 走得是$browser.safari 這個判斷,因爲谷歌啓用了新版的內核,應該是使用蘋果的safarie。所以這個判斷對新版谷歌有問題
    //Opera
    if($browser.opera){}
    //IE6 -
    if($browser.msie&&$browser.version<=6){}
    //IE6 +
    if($browser.msie&&$browser.version>6){}
});

如果使用jQuery 1.9版本之後,建議使用對應的原生javascript的判斷瀏覽器類型:

瀏覽器代碼名稱:navigator.appCodeName
    瀏覽器名稱:navigator.appName
    瀏覽器版本號:navigator.appVersion
    對Java的支持:navigator.javaEnabled()
    MIME類型(數組):navigator.mimeTypes
    系統平臺:navigator.platform
    插件(數組):navigator.plugins
    用戶代理:navigator.userAgent
<script type="text/javascript">

        var Sys = {};

        var ua = navigator.userAgent.toLowerCase();

        var s;

        (s = ua.match(/msie ([\d.]+)/)) ? Sys.ie = s[1] :

        (s = ua.match(/firefox\/([\d.]+)/)) ? Sys.firefox = s[1] :

        (s = ua.match(/chrome\/([\d.]+)/)) ? Sys.chrome = s[1] :

        (s = ua.match(/opera.([\d.]+)/)) ? Sys.opera = s[1] :

        (s = ua.match(/version\/([\d.]+).*safari/)) ? Sys.safari = s[1] : 0;



        //以下進行測試

        if (Sys.ie) document.write('IE: ' + Sys.ie);

        if (Sys.firefox) document.write('Firefox: ' + Sys.firefox);

        if (Sys.chrome) document.write('Chrome: ' + Sys.chrome);

        if (Sys.opera) document.write('Opera: ' + Sys.opera);

        if (Sys.safari) document.write('Safari: ' + Sys.safari);

    </script>

4.文本框文字獲取和失去焦點

$(document).ready(function(){
    $("input.text").val("請輸入文字內容...");
    textWaterMark($("input.text"));
});
function textWaterMark(txtObj)
{
    var origVal=txtObj.val();
    txtObj.focus(function(){
     if($.trim(txtObj.val())==origVal){
            txtObj.val('');
        }
    }).blur(function(){
        if($.trim(txtObj.val())==origVal){
            txtObj.val(origVal);
        }
    });
}

5.返回頂部動畫

jQuery.fn.scrollTo=function(speed){
    var targetOffSet=$(this).offset().top();
    $("html,body").stop().animate({scrollTop:targetOffset},speed);
    return this;
};
$("#goheader").click(function(){
    $("body").scrollTo(500);
    return false;//防止冒泡
});

6.獲取鼠標的位置和左右鍵

$(document).ready(function(){
      //鼠標位置
    $(document).mousemove(function(e){
      $("#testmousepos").html("X:"+e.pageX+",Y:"+e.pageY);
    });
    //鼠標左右鍵
    $("#testmousedown").mousedown(function(e){
      $(this).html(e.which); //1:鼠標左鍵;2:鼠標中鍵(滾輪);3:鼠標右鍵
    });
});

js的原生方法,可以參考這篇文章:
http://www.cnblogs.com/dolphinX/archive/2012/10/09/2717119.html

7.判斷元素是否存在

$(document).ready(function(){
    if($("#id").length>0){} //建議使用>0 的方式,因爲$("#id")返回的是一個jquery對象,而length返回的是個數,但是我在個別瀏覽器測試下只有>0的才走裏面的代碼,到現在也不知道爲何。
});

8.點擊某些html元素跳轉(div span等)

<span><a href="https://www.google.com"></a></span>;
$("span").click(function(){
    windows.location.href=$(this).find("a").attr("href");
    retrun false;
});

9.根據瀏覽器大小添加不同的樣式

  jQuery.fn.checkWindowSize=function(){
    if($(window).width()>1200){
       $('body').addClass('bodyClass');
    }
    else{
     $('body').removeClass('bodyClass');
    }
    return this;
};
$(document).ready(function(){
   $(window).checkWindowSize();
});

10.設置元素在屏幕中心

 jQuery.fn.center=function(){
    this.css("position","absolute");
    this.css("top",($(window).height()-this.height())/2+$(window).scrollTop()+"px");

    this.css("left",($(window).width()-this.width())/2+$(window).scrollLeft()+"px");
    return this;
};
$(document).ready(function(){
   $("#id").center();
});

11.創建屬於自己的jQuery選擇器

$(document).ready(function(){
    $.extend($.expr[":"],{
       widthgt100:function(obj){
           return $(obj).width()>100;
       };
    });
$("#id:widthgt100").click(function(){});
});

12.設置jQuery全局參數

$(document).ready(function(){
  //關閉動畫效果
  jQuery.fx.off=true;

   //設置全局進度條 這樣就在ajax請求時會自動加載進度條 不必每個方法都寫了
   var $loading = $("#loading");
        var $document = $(document);
        $document.ajaxStart(function () {
            if ($loading.length>0) {
                showLoading();
            }
        });
        $document.ajaxStop(function () {          
            if ($loading.length>0) {
                hideLoading();
            }
        });  
        $document.ajaxComplete(function () {          
            if ($loading.length>0) {
                hideLoading();
            }
        });   //簡單提一下ajaxStop和ajaxComplete  ajaxStop 是頁面所有的ajax結束時 進度條纔會關閉,意味着每發送一個請求等效於隊列中增加一個showLoading。出現錯誤時也不會關閉。 而ajaxComplete是頁面有一個ajax請求結束進度條就會隱藏,那麼有錯誤的情況下。所以讀者要根據自己的實際情況 考慮使用那個全局方法。

        $document.ajaxError(function (event, jqxhr, settings, thrownError) {
            console.log(settings.url + " " + jqxhr.status + " " + jqxhr.statusText);
            console.log(thrownError);
        });
    //設置某頁面全局ajax同步/異步方式
         $.ajaxSetup({
                    async: false
                }); //設置本頁請求爲同步模式
});

還有一部分全局函數可以參考如下網站:
http://www.css88.com/jqapi-1.9/category/ajax/global-ajax-event-handlers/

13.回車提交事件

$(document).ready(function(){
    $("#id").keyup(function(e){
        if(e.which=="13"){}
    });
});

14.使用siblings()來選擇同輩元素

建議看看這篇文章:http://blog.csdn.net/u010533180/article/details/53816040

//較差的做法
$("#id li").click(function(){
    $(#id li).removeClass("active");
    $(this).addClass("active");
});
//好的寫法
$("#id li").click(function(){
    $(#id li).addClass("active").siblings().removeClass("active");
});

15.控制檯輸出日誌

jQuery.log=jQuery.fn.log=function(msg){
    if(console)//考慮到微軟家族部分瀏覽器不支持console函數,坑爹的很
    {
        console.log("%s:%o",msg,this);
    }
    return this;
};

16.爲選擇器匹配的元素綁定事件

例如給table裏面的td元素綁定click事件,不管td元素是一直存在還是動態創建

建議諮詢看看這篇文章第7條內容
http://blog.csdn.net/u010533180/article/details/53816040

//jquery 1.4.2之前的使用方式
$("#table").each(function(){
    $("td",this).live("click",function(){
        $(this).toggleClass("hover");
    });
});

//jquery 1.4.2的使用方式
$("#table").delegate("td","click",function(){
    $(this).toggleClass("hover");
}
});

//jquery 1.7.1的使用方式
$("#table").on("click","td",function(){
    $(this).toggleClass("hover");
}
});

17.使用css鉤子

jquery.cssHooks是1.4.3版本新增的方法,當自定義新的css Hooks時實際上定義的是getter和setter 方法。比如:border-radius 這個圓角屬性想要成功應用於firefox、webkit等瀏覽器,需要增加前綴,例如:-moz-border-radius和-webkit-border-radius。這可以通過自定義css hooks將其封裝成統一的接口borderRadius,而不是逐一設置屬性。更多cssHooks可以查看
https://github.com/brandonaaron/jquery-cssHooks

$.cssHooks["borderRadius"]={
    get:function(elem,computed,extra){
     //根據瀏覽器支持的屬性進行獲取對應的屬性值
     //-moz-border-radius  -webkit-border-radius。
    },
    set:function(elem,value){
        //設置屬性值
    }
};
$("#id").css("borderRadius",5);

18.限制Text-Area域中的字符的個數

jQuery.fn.maxLength = function(max){
    this.each(function(){
        var type = this.tagName.toLowerCase();
        var inputType = this.type? this.type.toLowerCase() : null;
        if(type == "input" && inputType == "text" || inputType == "password"){
            //使用空軍自身的屬性設置
            this.maxLength = max;
        }
        else if(type == "textarea"){
            this.onkeypress = function(e){
                var ob = e || event;
                var keyCode = ob.keyCode;
                var hasSelection = document.selection? document.selection.createRange().text.length > 0 : this.selectionStart != this.selectionEnd;
                return !(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13) && !ob.ctrlKey && !ob.altKey && !hasSelection);
            };
            this.onkeyup = function(){
                if(this.value.length > max){
                    this.value = this.value.substring(0,max);
                }
            };
        }
    });
};
//用法
$('#mytextarea').maxLength(100);

19.使用HTML5本地存儲功能

本地存儲是HTML 5 提供的新特性之一,提供了非常簡單的API接口,便於添加你的數據到localStoreage全局屬性中,便於緩存查找,減少服務器的壓力。代碼如下:

localStorage.someData="本地緩存內容";

對於一些老的瀏覽器可能不支持,可以使用jquery 插件來提供支持。
https://plugins.jquery.com/storageapi/

20.從元素中除去HTML

        (function ($) {
            $.fn.stripHtml = function () {
                var regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi; this.each(function () {
                    $(this).html($(this).html().replace(regexp, ""));
                }); return $(this);
            }
        })(jQuery);

21 擴展String方法

 $.extend(String.prototype, {
            append: function (str) {
                return this.concat(str);
            },
            /** 刪除指定索引位置的字符,索引無效將不刪除任何字符 **/
            deleteCharAt: function (index) {
                if (index < 0 || index >= this.length) {
                    return this.valueOf();
                }
                else if (index == 0) {
                    return this.substring(1, this.length);
                }
                else if (index == this.length - 1) {
                    return this.substring(0, this.length - 1);
                }
                else {
                    return this.substring(0, index) + this.substring(index + 1);
                }
            },
            isPositiveInteger: function () {
                return (new RegExp(/^<1-9>\d*$/).test(this));
            },
            isInteger: function () {
                return (new RegExp(/^\d+$/).test(this));
            },

            isNumber: function (value, element) {
                return (new RegExp(/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/).test(this));
            },
            trim: function () {
                return this.replace(/(^\s*)|(\s*$)|\r|\n/g, "");
            },
            trans: function () {
                return this.replace(/&lt;/g, '>').replace(/"/g, '"');
            },
            replaceAll: function (os, ns) {
                return this.replace(new RegExp(os, "gm"), ns);
            },
            skipChar: function (ch) {
                if (!this || this.length === 0) { return ''; }
                if (this.charAt(0) === ch) { return this.substring(1).skipChar(ch); }
                return this;
            },

            isValidPwd: function () {
                return (new RegExp(/^(<_>|){6,32}$/).test(this));
            },

            isValidMail: function () {
                return (new RegExp(/^\w+((-\w+)|(\.\w+))*\@+((\.|-)+)*\.+$/).test(this.trim()));
            },

            isSpaces: function () {
                for (var i = 0, len = this.length; i < len; i++) {
                    var ch = this.charAt(i);
                    if (ch != ' ' && ch != "\n" && ch != "\t" && ch != "\r") { return false; }
                }
                return true;
            },

            isPhone: function () {
                return (new RegExp(/(^(<0-9>{3,4}<->)?\d{3,8}(-\d{1,6})?$)|(^\(<0-9>{3,4}\)\d{3,8}(\(\d{1,6}\))?$)|(^\d{3,8}$)/).test(this));
            },

            isUrl: function () {
                return (new RegExp(/(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/g)).test(this);
            },

            isExternalUrl: function () {
                return this.isUrl() && this.indexOf("://" + document.domain) == -1;
            }
        });

也可以把如下鏈接中的方法擴展到其中
http://www.cnblogs.com/sntetwt/p/4208306.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章