• 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");


    运行效果:

  • 相关阅读:
    在 mac iTerm2 中使用 cmd 终端
    在 jupyter 中添加菜单和自动完成功能
    Bash 和 Zsh 开启 vi-mode
    免密登录和远程执行命令
    图片的筛选
    win10 右键菜单很慢的解决方式
    ssh中的 Connection closed by ***
    NodeJS 获取网页源代码
    在 JSDOM v11 中使用jQuery
    kafaka学习
  • 原文地址:https://www.cnblogs.com/liulinjie/p/11024100.html
Copyright © 2020-2023  润新知