兼容IE8的方法函数

By AYE 0
  1. 兼容IE8 数组的 forEach

    if ( !Array.prototype.forEach ) {
        Array.prototype.forEach = function forEach( callback, thisArg ) {
            var T, k;
            if ( this == null ) {
                   throw new TypeError( "this is null or not defined" );
            }
            var O = Object(this);
            var len = O.length >>> 0; 
            if ( typeof callback !== "function" ) {
                throw new TypeError( callback + " is not a function" );
            }
            if ( arguments.length > 1 ) {
                T = thisArg;
            }
            k = 0;
            while( k < len ) {
                var kValue;
                if ( k in O ) {
                    kValue = O[ k ];
                    callback.call( T, kValue, k, O );
                }
                k++;
            }
        };
    }
  2. 兼容IE8 数组的 indexOf

    if ( !Array.prototype.indexOf ) {
        Array.prototype.indexOf = function( elt /*, from*/ ) {
            var len = this.length >>> 0;
            var from = Number( arguments[1] ) || 0;
            from = (from < 0)
                ? Math.ceil(from)
                : Math.floor(from);
            if (from < 0) from += len;
            for ( ; from < len; from++ ) {
                if ( from in this && this[from] === elt) return from;
            }
            return -1;
        };
    }
  3. 兼容bind函数

    if ( !Function.prototype.bind ) {
        Function.prototype.bind = function() {
            if ( typeof this !== 'function' ){
                throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
            }
            var _this = this;
            var obj = arguments[0];
            var ags = Array.prototype.slice.call( arguments, 1 );
            return function() {
                _this.apply( obj,ags );
            };
        };
    }
  4. 兼容IE8的getElementsByClassName函数

    if ( !document.getElementsByClassName ) {
        document.getElementsByClassName = function ( className, element ) {
            var children = ( element || document ).getElementsByTagName('*');
            var elements = new Array();
            for ( var i = 0; i < children.length; i++ ) {
                var child = children[i];
                var classNames = child.className.split(' ');
                for ( var j = 0; j < classNames.length; j++ ) {
                    if ( classNames[j] == className ) {
                        elements.push(child);
                        break;
                    }
                }
            }
            return elements;
        };
    }
  5. 兼容IE8的addEventListener函数

    function addEventListener( ele,event,fn ){
        if( ele.addEventListener ) {
            ele.addEventListener( event, fn, false );
        } else {
            ele.attachEvent( 'on'+event, fn.bind(ele) );
        }
    }