jQuery封装init

var quickExpr = /^[^<]*(<(.|\s)+>)[^>]*$|^#(\w+)$/;

以上这个是一个检测HTML字符串和ID字符串的简单正则判断方法。


实例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    
</body>
</html>
<script>
    (function(){
        //以下两行是为了防止之前的有这两个变量
        var _jQuery = window.jQuery;
        var _$ = window.$;

        var jQuery = window.jQuery = window.$ = function(selector,context){
            return new jQuery.fn.init(selector,context);
        }
        
        var quickExpr = /^[^<]*(<(.|\s)+>)[^>]*$|^#(\w+)$/;
        //下面这个是jQuery的初始化函数. 每次new 一个jQuery对象的时候,
        //总是首先由这个函数实现初始化.
        jQuery.fn = jQuery.prototype = {

            init:function(selector,context){
                selector = selector || document;
                /*
                * 下面要对selecotr对象进行进行分类的检查,不同类型,不同的处理.
                * selector可能的类型如下:
                * (1) 直接的一个Dom元素类型
                * (2) 数组类型
                * (3) 函数(function)类型
                * (4) jQuery或者其他的类数组对象类型
                * (5) string类型
                * a) 没有context的情况
                * b) 有context的情况
                */
                if(selector.nodeType){
                    this[0] = selector;
                    this.length = 1;
                    return this;
                }

                if(typeof selector == 'string'){
                    // 如果exec() 找到了匹配的文本,则返回一个结果数组。否则,返回 null。
                    var match = quickExpr.exec( selector );

                    if ( match && (match[1] || !context) ){
                        if ( match[1] )
                            selector = jQuery.clean( [ match[1] ], context );
                        else{
                            var elem = document.getElementById( match[3] );
                            if(elem){
                                if ( elem.id != match[3] ){
                                    return jQuery().find( selector );                                
                                }
                                return jQuery( elem );
                            }
                        }
                    }else{
                        return jQuery( context ).find( selector );
                    }
                }else if ( jQuery.isFunction( selector ) ){
                    return jQuery( document )[ jQuery.fn.ready ? "ready" :"load" ]( selector );
                }
                return this.setArray(jQuery.makeArray(selector));
            }
        }      

        
        jQuery.fn.init.prototype = jQuery.fn;
    }())
</script>







猜你喜欢

转载自blog.csdn.net/qq_34559257/article/details/80329984