在上篇介绍了选择器的获取标签、id、类名的方法,现在我们在上篇基础上继续升级

1、问题描述:上篇get('选择器')已经实现,如果get方法里是一个选择器的父元素,父元素是DOM对象,那么如何获取元素

思路:1、首先想到的是标签、id、类名的三个方法  2、假设是body节点,那么方法中的document改成body 3、传入的参数如何判断是否为DOM

注意:在获取id方法中全局也只有一个id,所以其中的doument无须修改

修改如下

// 注释: 对获取DOM对象方法的封装
var getTag = function ( tag, context, results ) {
    results = results || [];
    context = context || document;//防止context是空时报错现象出现
    
    results.push.apply( results, context.getElementsByTagName( tag ) );
    return results;
};

var getId = function ( id, results ) {
    results = results || [];
    results.push( document.getElementById( id ) );
    return results;
};

var getClass = function ( className, context, results ) {
    results = results || [];
    context = context || document;
    if ( document.getElementsByClassName ) {
        results.push.apply( results, context.getElementsByClassName( className ) );
    } else {
        each( getTag( '*', context ), function ( i, v ) {
            if ( ( ' ' + v.className + ' ' )
                        .indexOf( ' ' + className + ' ' ) != -1 ) {
                results.push( v );
            }
        } );
    }
    return results;
};


// 对each方法的封装
var each = function ( arr, fn ) {
    for ( var i = 0; i < arr.length; i++ ) {
        if ( fn.call( arr[ i ], i, arr[ i ] ) === false ) {
            break;
        }
    }
};
        
// 通用的get方法
var get = function ( selector, context, results ) {
    results = results || [];
    var rquickExpr = /^(?:#([\w-]+)|\.([\w-]+)|([\w]+)|(\*))$/,
        m = rquickExpr.exec( selector );
    
    if ( m ) {    
        if ( m[ 1 ] ) {
            results = getId( m[ 1 ], results );
        } else if ( m[ 2 ] ) {
            results = getClass( m[ 2 ], context, results );
        } else if ( m[ 3 ] ) {
            results = getTag( m[ 3 ], context, results );
        } else if ( m[ 4 ] ) {
            results = getTag( m[ 4 ], context, results );
        }
        
    }
View Code

相关文章:

  • 2022-12-23
  • 2021-10-14
  • 2021-08-19
  • 2021-06-21
  • 2021-08-15
  • 2021-10-01
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-24
  • 2021-11-12
相关资源
相似解决方案