zoukankan      html  css  js  c++  java
  • 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");


    运行效果:

  • 相关阅读:
    HDU 1261 字串数(排列组合)
    Codeforces 488C Fight the Monster
    HDU 1237 简单计算器
    POJ 2240 Arbitrage
    POJ 3660 Cow Contest
    POJ 1052 MPI Maelstrom
    POJ 3259 Wormholes
    POJ 3268 Silver Cow Party
    Codesforces 485D Maximum Value
    POJ 2253 Frogger(最短路)
  • 原文地址:https://www.cnblogs.com/liulinjie/p/11024100.html
Copyright © 2011-2022 走看看