目 录CONTENT

文章目录

jQuery扩展方法

Administrator
2020-07-24 / 0 评论 / 0 点赞 / 12734 阅读 / 9976 字 / 正在检测是否收录...

jQuery扩展方法

jQuery的扩展方法分为两种情况扩展

  1. 直接在jQuery的对象上面进行扩展
  2. 在jQuery选择器结果上面去扩展

在jQuery的对象上面扩展方法

jQuery在内部提供一种机制,可以直接在原有的框架上面去扩展方法,这个方法是$.extend(),它接收一个对象做为参数

$.extend({
    方法1:function(){
        
    },
    方法2:function(){
        
    }
})

在一般情况之下,如果我们真的要扩展jQuery的方法,我们一般都是这么做的

  1. 第一步:先新建一个js文件叫jQuery.extend.js
  2. 第二步:在这个js文件里面去进行方法的扩展,代码如下
/**
 * @description jQuery的扩展方法
 */
(function($){
    $.extend({
        /**
         * @name myForEach 自己的forEach方法
         * @param {Array} arr 要遍历的数组
         * @param {function} callBack 遍历的回调函数
         */
        myForEach:function(arr,callBack){
            if(arguments.length<2){
                //参数不是2个
                throw new Error("参数不对");
            }
            else{
                for(var i=0;i<arr.length;i++){
                    //i代表当前索引 
                    //arr[i] 代表当前遍历的元素
                    callBack(i,arr[i]);
                }
            }
        }
    })
})(jQuery);

方法是一个封闭的环境 ,所以我们使用了立即执行函数的闭包(本质就是立即执行的匿名函数),如果这个闭包使用到了外部的变量,我们就把这个变量当成参数给传递进去

在jQuery的选择器上面扩展方法

jQuery通过选择器选中元素以后可以返回结果,如果要在选中的结果上面去扩展方法,这个时候就要找$.fn.extend()

/**
 * @description jQuery的扩展方法
 */

(function($){
    //在jQuery对象上面扩展
    $.extend({
        /**
         * @name myForEach 自己的forEach方法
         * @param {Array} arr 要遍历的数组
         * @param {function} callBack 遍历的回调函数
         */
        myForEach:function(arr,callBack){
            if(arguments.length<2){
                //参数不是2个
                throw new Error("参数不对");
            }
            else{
                for(var i=0;i<arr.length;i++){
                    //i代表当前索引 
                    //arr[i] 代表当前遍历的元素
                    callBack(i,arr[i]);
                }
            }
        }
    });
    //在选择器上面扩展
    $.fn.extend({
        htmlAll:function(){
            // console.log(this);
            //这个时候this指向的是你选中的元素的结果 $(".ul1>li")这个结果
            var resultArr=[];
            this.each(function(index,item){
                resultArr.push($(item).html());
            });
            return resultArr;
        }
    })
})(jQuery);

通过jQuery扩展方法实现jQuery的第一个插件

现在我们通过jQuery去写了一个自定义的右键菜单,但是这个菜单并不能实现通用化的效果

1567990958758

该效果代码如下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>jQuery扩展方法</title>
    <style>
        .div1,.div2{
            width:200px;
            height:200px;
            border: 1px solid black;
        }
        .my-contextmenu{
            margin: 0px;
            padding: 0px;
            list-style-type: none;
            width: 130px;
            border: 1px solid lightgray;
            position:fixed;
            left:0px;
            top:0px;
            background-color:white;
            box-shadow:0px 0px 5px 3px lightgray;
            
        }
        .my-contextmenu li{
            height:30px;
            border-top:1px solid lightgray;
            text-align:center;
            line-height:30px;
            font-size:14px;
            cursor:pointer;
        }
        
        .my-contextmenu li:nth-child(even){
            background-color:#ececec;
        }
        .my-contextmenu li:hover{
            background-color:lightskyblue;
            font-weight:bold;
        }
    </style>
</head>
<body>
    <div class="div1">

    </div>
    <ul class="my-contextmenu">
        <li>去百度</li>
        <li>弹窗</li>
        <li>打印你好</li>
        <li>询问框</li>
    </ul>

    <hr />

    <div class="div2"></div>
</body>
<script src="./js/jquery.js" type="text/javascript"></script>
<script>
    $(function(){
        $(".div1").on("contextmenu",function(event){
            event.preventDefault();  //阻止事件的默认行为
            console.log(event);
            //现在先模拟一个右键菜单
            var x=event.clientX;
            var y=event.clientY;
            $(".my-contextmenu").css({
                left:x+"px",
                top:y+"px"
            }).show(200);
        });
         $(document).click(function(){
            $(".my-contextmenu").hide();
        })
         //-------假设我们写固定死,应该怎么写-------
         $(".my-contextmenu>li").click(function(){
             var index=$(this).index();
             if(index==0){
                location.href="http://www.baidu.com";
             }
             else if(index==1){
                alert("你好");
             }
             else if(index==2){
                console.log("你好");
             }else if(index==3){
                confirm("我在问你");
             }
         })
    });
</script>
</html>

它没有实现做对的可移植性与通用化,这个时候,如果我们想在其它的地方也去实现一个这样的右键菜单,这个时候,我们发现上面的代码我们又要重新的写一次

这个时候,我们就要考虑能不能把上面的右键菜单进行封装,实现导入即用

$(".div1").addContextMenu()

核心JS代码

/**
* @name addContextMenu 添加右键菜单方法
*/
(function ($) {
   $.fn.extend({
       /**
        * @author 杨标
        * @param {Array} config 右键菜单配置,以对象为单位,text属性代表右键菜单文本,fn属性代表单击以后的回调方法 {text:string,fn:callBack}
        */
       addContextMenu: function (config) {
           //选创建右键菜单
           if (config instanceof Array) {
               var ul = document.createElement("ul");
               ul.className = "my-contextmenu";
               $.each(config,function(index,ele){
                   var li=document.createElement("li");
                   li.innerHTML=ele.text;
                   $(li).click(ele.fn);
                   ul.appendChild(li);
               });
               document.body.appendChild(ul);
           }
           //右键菜单创建完毕
           this.on("contextmenu",function(event){
               //阻止事件的默认行为
               event.preventDefault();
               var x=event.clientX;
               var y=event.clientY;
               $(ul).css({
                   left:x+"px",
                   top:y+"px"
               }).show(200).siblings(".my-contextmenu").hide();
           });
           $(document).click(function(){
               $(".my-contextmenu").hide();
           });
       }
   })
})(jQuery);

与之对应的CSS代码

@charset "utf-8";
/*配置jQuery.contextmenu.js一起使用,实现自定义的右键菜单效果*/
.my-contextmenu{
    margin: 0px;
    padding: 0px;
    list-style-type: none;
    width: 130px;
    border: 1px solid lightgray;
    position:fixed;
    left:0px;
    top:0px;
    background-color:white;
    box-shadow:0px 0px 5px 3px lightgray;
    display:none;
}
.my-contextmenu li{
    height:30px;
    border-top:1px solid lightgray;
    text-align:center;
    line-height:30px;
    font-size:14px;
    cursor:pointer;
}

.my-contextmenu li:nth-child(even){
    background-color:#ececec;
}
.my-contextmenu li:hover{
    background-color:lightskyblue;
    font-weight:bold;
}

我们将上面的js方便命名为jQuery.contextmenu.js,将CSS文件命名为jQuery.contextmenu.css,它们一套,同时使用的,如果要使用这个右键菜单,我们必须同时导入上面的JS与CSS文件

测试代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>jQuery扩展方法右键菜单</title>
    <link rel="stylesheet" href="./js/jquery_contextmenu/jQuery.contextmenu.css">
    <style>
        .div1,.div2{
            width:200px;
            height:200px;
            border: 1px solid black;
        }
    </style>
</head>
<body>
    <div class="div1">

    </div>
    <hr />

    <div class="div2"></div>
</body>
<script src="./js/jquery.js" type="text/javascript"></script>
<script src="./js/jquery_contextmenu/jQuery.contextmenu.js"></script>
<script>
   $(function(){
       //在div1上面添加右键菜单
       $(".div1").addContextMenu([{
           text:"提交",
           fn:function(){
               alert("你提交了,所以要去百度");
               location.href="http://www.baidu.com";
           }
        },{
            text:"退回",
            fn:function(){
                console.log("你要退回");
            }
        }]);
		//在div2上面添加右键菜单
        $(".div2").addContextMenu([{
            text:"测试",
            fn:function(){
                console.log("测试")
            }
        }]);
   })
</script>
</html>

注意:在导入我们刚刚编写的插件的时候,要注意一个问题,应该先导入jQuery再去导入我们自己编写的插件jQuery.contextmenu.js。同时以后导入所以的jQuery插件都是先导jQuery再导插件

0

评论区