javascript 仿jQuery的无new构造函数

Javascript 748 0 2020-10-12

javascript 仿jQuery的无new构造函数

/* 匿名函数 传入 window 值全局变量成为局部变量 */

   (function(window,undefined) {

       /* 申明一个名为jQuery 的函数*/

       function jQuery(selector) {

           /* 返回 jQuery 实例 */

           return new jQuery.prototype.init(selector);

       }

       /* 为jQuery函数原型添加一个初始化 init 方法 */

       jQuery.prototype.init=function (selector) {

           this.el=document.querySelectorAll(selector)[0];

       };

       /* 为jQuery函数原型添加一个 html 方法 */

       jQuery.prototype.html=function(str){

           if(str){

               this.el.innerHTML=str;

           }else {

               return this.el.innerHTML;

           }

           return this;

       };

       /* 为jQuery函数原型添加一个 color 方法 */

       jQuery.prototype.color=function(rgb){

           if(rgb){

               this.el.style.color=rgb;

           }

           return this;

       };

       /* 将jQuery的原型 赋值给初始化方法的原型*/

       jQuery.prototype.init.prototype = jQuery.prototype;

       /* 设置jQuery函数的别名 $ 并设置为window全局对象的属性 */

       window.$=window.jQuery=jQuery;

   })(window,undefined);


<!-- html -->

<div id="div1">123</div>


<!-- js -->

$("#div1").html('<h1>helang.love@qq.com</h1>').color("#ff0000");

运行效果:

上一篇:Chart.js 图表数据背景线条颜色设置

下一篇:javascript - 实现jquery类似的$调用方法

讨论数量:0

请先登录再发表讨论。 2024-04-24

天涯网魂
3 杠 5 星
TA 的文章
TA 的随言
TA 的资源链