模仿jQuery方式获取节点;模仿jQuery方式生成方法;扩展方法

本文介绍了一种使用原生JavaScript封装节点获取和操作的方法,通过减少代码量和提供常用功能,如HTML和CSS操作,以及AJAX和扩展方法,提高了开发效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

利用原生js获取节点需要重复相同获取节点的代码,使得代码量变大,封装之后获取节点就非常的方便,该方法不仅能获取节点,还能生成一些常用的方法,方便后期调用,减少代码量,优化开发效率。

        (function (){
            // 初始化
            function init(selector){
                return new jqruy(selector)
            }
            // 生成节点
            function jqruy(selector){
                this.node='';//节点
                if (/^#/.test(selector)){
                    // console.log(selector.substring(1))
                    this.node=document.getElementById(selector.substring(1))
                }else if (/^\./.test(selector)){
                    this.node=document.getElementsByClassName(selector.substring(1))
                }else if(/\d/.test(selector)){
                    this.node=document.getElementsByTagName(selector)
                }
            }
            // 添加方法
            jqruy.prototype.html=function (str){
                this.node.innerHTML=str
            }
            jqruy.prototype.css=function (attr,value){
                this.node.style.attr=value
            }
            // 为init函数添加方法
            init.ajax=function (str){
                // this.node.innerHTML=str
                console.log('ajax')
            }
            // 扩展方法
            init.extend=function (obj){
                console.log(obj)
                for(let key in obj){
                    init[key]=obj[key]
                }
            }
            window.$= init
        })()
        $('#on').html()//调用html方法
        $('#on').css()//调用css方法
        $.ajax()//调用方法
    //     扩展方法
        $.extend({
            each:function (){
                console.log("each")
            },
            newFn:function (){
                console.log("newFn")
            }
        })
        $.each();
        $.newFn();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值