jQuery工具函數


一、$.browser對象屬性

  屬性列表                  說明

  webkit       webkit相關瀏覽器則返回true,否則返回false,如google,傲游。

  mozilla       mozilla相關瀏覽器則返回true,否則返回false,如火狐

  safari         safari相關瀏覽器則返回true,否則返回false,如safari

  opera        opera相關瀏覽器則返回true,否則返回false,如opera

  msie        msie相關瀏覽器則返回true,否則返回false,如IE,360,搜狗

  version       返回對應瀏覽器的版本

        $(function () {
            if ($.browser.msie) {
                alert("IE瀏覽器");
            }
            if ($.browser.webkit) {
                alert("webkit瀏覽器");
            }
            if ($.browser.mozilla) {
                alert("mozilla瀏覽器");
            }
            if ($.browser.safari) {
                alert("safari瀏覽器");
            }
            if ($.browser.opera) {
                alert("opera瀏覽器");
            }
            alert($.browser.version);
        })

二、boxModel

  返回一個布爾值,如果是W3C盒子模型則返回true,否則返回false。

  盒子模型分兩類,一類是W3C盒子模型,一類是IE盒子模型。兩者的根本區別在於W3C的盒子模型不包括padding與border,僅指content的Height和Width,而IE盒子模型  包含padding與border。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="jQuery.1.8.3.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            if ($.support.boxModel) {
                alert("W3C盒子模型!");
            }
            else {
                alert("IE盒子模型!");
            }
        })
    </script>
</head>
<body>

</body>
</html>

  上面的例子彈出W3C盒子模型,如果刪除掉頂部的兩行,<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml">。則彈出的是IE盒子模型。

數組和對象的操作

三、$.each()

  此工具函數不僅能夠完成指定數組的遍歷,還能夠實現頁面中元素的遍歷。

  語法:$.each(obj,fn(para1,para2))  obj要遍歷的數組或對象,fn為每個遍歷元素執行的回調函數,para1表示數組的序號或對象的屬性,para2表示數組的元素和對象的屬性。

        $(function () {
            var arr = [1, 2, 3, 4, 5];
            $.each(arr, function (index, value) {
                document.write(index + ":");
                document.write(value + "<br/>");
            });
        })
    輸出:
      0:1
      1:2
      2:3
      3:4
      4:5

  $.each()遍歷數組。

        $(function () {
            var arr = { "張三": "23","李四": 22,"王五": "21" };
            $.each(arr, function (index, value) {
                document.write(index + ":");
                document.write(value + "<br/>");
            });
        })
    輸出:張三:23
       李四:22
       王五:21

   元素遍歷

<head>
    <title></title>
    <script src="jQuery.1.8.3.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $("p").each(function () {
                $(this).css("background-color", "red");
            });

       //一下三行代碼與以上三行效果一樣 //$.each($("p"), function () { // $(this).css("background-color", "red"); //}) }) </script> </head> <body> <p>我是第一個P</p> <p>我是第二個P</p> <p>我是第三個P</p> <p>我是第四個P</p> <p>我是第五個P</p> </body> </html>

四、$.grep()

  篩選符合條件的元素,返回一個新數組

    語法:$.grep(Arrar,fn(value,index));  要注意下回調函數的參數的順序,第一個是值,第二個是索引。

       $.grep(Arrar,fn(value,index),[bool]);  第三個參數表示是否取反,true表示取反,false表示不取反。

        $(function () {
            var arr = [2, 5, 34, 22, 8];
            var arr1 = $.grep(arr, function(value, index) {
                return index <= 2 && value < 10;
            })
            document.write(arr1.join());  //輸出2,5
        })

六、$.map()

  改變函數內的數據,接受一個數組或類數組對象作為參數

        $(function () {
            var arr = [2, 5, 34, 22, 8];
            var arr1 = $.map(arr, function (value, index) {
                if (value > 5 && index < 3) {
                    return value - 10;
                }
            })
            document.write(arr.join() + "<br/>");  //2,5,34,22,8  可以看到原數組不改變
            document.write(arr1.join());        //24  新數組只獲得了操作之后的結果
        })

七、$.inArray()

  如果數組中存在被搜索元素,則返回被搜索元素的索引

        $(function () {
            var arr = [1, 2, 3, 4, 5];
            alert($.inArray(4,arr));  //彈出 3
        })

 八、$.trim()

  去除字符串兩邊的空格

        $(function () {
            var str = " 你在他鄉還好嗎? ";
            document.write("11" + str + "11" + "<br/>");  //輸出 11 你在他鄉還好嗎? 11
            document.write("11" + $.trim(str) + "11");   //輸出 11你在他鄉還好嗎?11    //加個11是為了看清楚差別。
        })

九、測試操作

    $.isArray(obj)    檢測參數是否是數組

    $.isFunction(obj)   檢測參數是否是一個函數

    $.isEmptyObject(obj)  檢測參數是否是一個空對象

    $.isPlainObject(obj)   檢測參數是否是一個純粹對象,即對象是否通過{}或new Object()關鍵字創建。

    $.contains(container,contained)  檢測一個DOM節點是否包含另一個DOM節點。是則返回true否則表示false。注意參數是DOM對象並非jQuery對象。

        $(function () {
            var arr = [1, 2, 3, 2, 1];
            document.write(jQuery.isArray(arr));  //返回true
            var str = "123";
            document.write(jQuery.isArray(str));  //返回false
})
        $(function () {
            var f = fun1;
            alert($.isFunction(fun1));  //返回true
        })
        function fun1() { }
        $(function () {
            var obj1 = {};
            var obj2 = { name: "張飛" };
            alert($.isEmptyObject(obj1));  //返回true  obj1是空對象
            alert($.isEmptyObject(obj2));  //返回false  obj2不是空對象
        })
        $(function () {
            var obj1 = {};
            var obj2 = { name: "張飛" };
            var obj3 = new Object();
            var obj4 = null;
            alert($.isPlainObject(obj1));  //true  通過{}創建
            alert($.isPlainObject(obj2));  //true  通過{}創建
            alert($.isPlainObject(obj3));  //true  通過new Object()創建
            alert($.isPlainObject(obj4));  //flase  不是通過{}或new Object()創建
        })
        $(function () {
            alert($.contains($("#div1")[0],$("#p1")[0]));  //返回true,注意參數是DOM對象,並非jQuery對象
        })

十、$.param()

  序列化成url字符串

    $.param(obj,[bool]);  第二個參數為可選參數,表示是否淺層序列化

        $(function () {
            var man = { Name: "張飛", Age: 23 };
            var str = $.param(man);
            document.write(str);      //Name=%E5%BC%A0%E9%A3%9E&Age=23
            var str1 = decodeURI(str);
            document.write("<br>" + str1);  //Name=張飛&Age=23
        })

十一、$.makeArray()

  將數組或類數組對象的屬性復制到一個新的數組(真的是數組)中,並返回該新數組。

        var arr = [1,3,5,7,9];
        $(function () {
            var arr1 = $.makeArray(arr);
            document.write(arr1.join());  //輸出 1,3,5,7,9
        })

十二、$.merge()

  該函數接受兩個數組或類數組對象,將第二個參數附加到第一個參數上面,返回第一個參數,第一個數組會修改,第二個不會。

        var arr1 = [1, 3, 5, 7, 9];
        var arr2 = [2, 4, 6, 8, 10];
        $(function () {
            var arr3 = $.merge(arr1, arr2);
            document.write(arr1.join() + "<br/>");    //1,3,5,7,9,2,4,6,8,10
            document.write(arr2.join() + "<br/>");    //2,4,6,8,10
            document.write(arr3.join() + "<br/>");    //1,3,5,7,9,2,4,6,8,10
        })

十三、$.parseJSON()

  該函數會解析JSON格式的字符串,並返回解析結果(對象)。 類似於JSON.parse(),注意:jQuery只定義了JSON解析函數,並沒有定義序列化函數。

        var man = { name: "張三", age: 23 };
        var str = JSON.stringify(man);
        document.write(str + "<br/>");  //{"name":"張三","age":23}
        var man1 = $.parseJSON(str);
        document.write(man1.name + man1.age);   //張三23

十四、$.proxy()

  類似於Function對象的bind()方法,接受函數作為第一個參數,對象作為第二個參數,並返回一個新函數,該函數會作為第二個參數對象的方法調用。

  $(function () {
    var obj = {
      name: "John",
      test: function () {
        alert(this.name);    //當id為test的按鈕點擊時,彈出姓名
        $("#test").unbind("click", obj.test);  //並取消事件綁定(下次再點擊不會彈出姓名)
    }
  };
    $("#test").click(jQuery.proxy(obj, "test"));  //綁定object對象里面的方法test
  })

十五、$.unique(array)

  刪除元素數組中的重復元素

$(function () {
    var arr = [1, 2, 3, 2, 1];
    jQuery.unique(arr);
    alert(arr.join());  //返回  3,2,1
})

十六、$.extend()

  合並對象中的元素

$(function(){
    var result=$.extend({},{name:"Tom",age:21},    {name:"Jerry",sex:"Boy"});
  alert(result.name);    //輸出 Jerry 后面的會覆蓋前面的,result始終只是一個對象
})

  省略dest參數,extend方法原型中的dest參數是可以省略的,如果省略了,則該方法就只能有一個src參數,而且是將該src合並到調用extend方法的對象中去。

  要特別注意的一點是:后面的值會覆蓋前面同名的值。

$(function(){
    $.extend({
        hello:function(){alert('hello');}  //該方法只有一個參數,意味着將hello方法合並到jQuery全局對象中去
    });
    $.hello();    //彈出 hello
})

  命名空間示例:

$(function(){
    $.extend({net:{}});        //擴展一個命名空間
    $.extend($.net,{
        hello:function(){alert('hello');}    //將hello方法綁定到命名空間net里去
    })
    $.net.hello();    //通過net命名空間調用方法
})

  拷貝方法原型:

extend(boolean,dest,src1,src2,src3...)

  其中第一個參數boolean表示是否進行深層拷貝。

$(function(){
    var result=$.extend( true,  {},  
        { name: "John", location: {city: "Boston",country:"USA"} },  
        { last: "Resig", location: {state: "MA",country:"China"} } ); 
    alert(result.location.state);        //輸出 MA

    //result={name:"John",last:"Resig", location:{city:"Boston",state:"MA",county:"China"}}

    var result=$.extend( false,  {},  
        { name: "John", location: {city: "Boston",country:"USA"} },  
        { last: "Resig", location: {state: "MA",country:"China"} } ); 
    alert(result.location.city);        //輸出 undefined

    //result={name:"John",last:"Resig",location:{state:"MA",county:"China"}}    注意沒有city,只是合並了location,location里面的屬性不管
})

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM