2019/9/28 jquery plugin1

厉高逸
2023-12-01
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        div{
            width:200px;
            height:200px;
        }
    </style>
</head>
<body>
    <!--插件:使得代码可以重复利用   这一节讲定义jquery插件-->
    <p>选取一些任意元素并将背景设为随机色</p>
    <div></div>
    <div></div>
    <script src="../jQuery库/jquery-3.4.1 .js"></script>
    <script>
        //1  jquery插件定义在jQuery .fn的基础上
        //2  构造函数的protety上再定义函数  (如何解决命名冲突?)
        //3  得到的是伪数组,需要循环遍历jquery对象的元素
        //4  jquery是链式调用,函数需要返回(this)
        (function ($) {
            $.fn.extend({
                randomColor:function () {
                    //this指向就是我们通过选择器选取的所有元素组成的伪数组
                    function random() {
                        var r = Math.floor(Math.random()* 256);
                        var g = Math.floor(Math.random()* 256);
                        var b = Math.floor(Math.random()* 256);
                        return 'rgb('+ r +','+ g +','+ b +')';
                    }
                    this.each(function (index){
                        $(this).css{
                            backgroundColor :random()
                        }

                    })
                   return this;
                }
            })
        })(jQuery)//这样解决命名冲突  $还是代表jQuery
        $('div').randomColor();
    </script>
</body
 类似资料: