面试篇---jq扩展自定义方法

  在一次面试中被面试官问到:你知道jq扩展吗?然后嘴贱就说了一句了解过一点点,然后面试官就继续的问下去。我就稀里糊涂的乱答了一通。

后面我就好好的去看了一下这个问题,下面也进行一个总结。仅供参考,如有瑕疵望指正。

       我直接贴代码:

<!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>xxx</title>
     <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
    
    <p>我可以改变颜色</p>
    <script>
        (function($){
            $.fn.extend({
                "changeColor":function(options){
                    var opts = $.extend({},defaults,options);
                    return this.each(function(){
                        var $this = $(this);
                        $this.css({
                            color:opts.color
                        });
                    });
                }
            });
            var defaults = {
                color:"red"
            }
        })(window.jQuery);
        
        $(function(){
            $("p").changeColor().css({marginTop:'100px'});
            console.log($("p"))
        })
    </script>
</body>
</html>
原文地址:https://www.cnblogs.com/justyouadmin/p/10639321.html