分类 JavaScript 下的文章

javascript常用的自定义函数

如果不使用类库或者没有自己的类库,储备一些常用函数总是有好处的。

1.$()

function $() {
    var elements = [];
    for (var i = 0; i < arguments.length; i++) {
        var element = arguments[i];
        if (typeof element == 'string')
            element = document.getElementById(element);
        if (arguments.length == 1)
            return element;
        elements.push(element);
    }
    return elements;
}

2.getStyle()与setStyle()

function setStyle(el,prop,value){
   if(prop == "opacity" && !+"\v1"){
     //IE7 bug:filter 滤镜要求 hasLayout=true 方可执行(否则没有效果)
     if (!el.currentStyle || !el.currentStyle.hasLayout) el.style.zoom = 1;
     prop = "filter";
     if(!!window.XDomainRequest){
       value ="progid:DXImageTransform.Microsoft.Alpha(style=0,opacity="+value*100+")";
     }else{
       value ="alpha(opacity="+value*100+")"
     }
   }
   el.style.cssText += ';' + (prop+":"+value);
 }
 
 function getStyle(el, style){
   if(!+"\v1"){
     style = style.replace(/\-(\w)/g, function(all, letter){
       return letter.toUpperCase();
     });
     return el.currentStyle[style];
   }else{
     return document.defaultView.getComputedStyle(el, null).getPropertyValue(style)
   }
 }

3.getCookie(), setCookie(), deleteCookie()

function getCookie( name ) {
    var start = document.cookie.indexOf( name + "=" );
    var len = start + name.length + 1;
    if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
        return null;
    }
    if ( start == -1 ) return null;
    var end = document.cookie.indexOf( ';', len );
    if ( end == -1 ) end = document.cookie.length;
    return unescape( document.cookie.substring( len, end ) );
}
function setCookie( name, value, expires, path, domain, secure ) {
    var today = new Date();
    today.setTime( today.getTime() );
    if ( expires ) {
        expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date( today.getTime() + (expires) );
    document.cookie = name+'='+escape( value ) +
        ( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
        ( ( path ) ? ';path=' + path : '' ) +
        ( ( domain ) ? ';domain=' + domain : '' ) +
        ( ( secure ) ? ';secure' : '' );
}
function deleteCookie( name, path, domain ) {
    if ( getCookie( name ) ) document.cookie = name + '=' +
            ( ( path ) ? ';path=' + path : '') +
            ( ( domain ) ? ';domain=' + domain : '' ) +
            ';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}

4.inArray()

var inArray = function (arr,value) {
    for (var i=0,l = arr.length ; i <l ; i++) {
        if (arr[i] === value) {
            return true;
        }
    }
    return false;
};

5.insertAfter()

function insertAfter(parent, node, referenceNode) {
    parent.insertBefore(node, referenceNode.nextSibling);
}

6.toggle()

function toggle(obj) {
    var el = document.getElementById(obj);
    if ( el.style.display != 'none' ) {
        el.style.display = 'none';
    }
    else {
        el.style.display = '';
    }
}

7.getElementsByClass()

var getElementsByClassName = function (searchClass, node,tag) {
    if(document.getElementsByClassName){
        return  document.getElementsByClassName(searchClass)
    }else{
        node = node || document;
        tag = tag || "*";
        var classes = searchClass.split(" "),
        elements = (tag === "*" && node.all)? node.all : node.getElementsByTagName(tag),
        patterns = [],
        returnElements = [],
        current,
        match;
        var i = classes.length;
        while(--i >= 0){
            patterns.push(new RegExp("(^|\\s)" + classes[i] + "(\\s|$)"));
        }
        var j = elements.length;
        while(--j >= 0){
            current = elements[j];
            match = false;
            for(var k=0, kl=patterns.length; k<kl; k++){
                match = patterns[k].test(current.className);
                if (!match)  break;
            }
            if (match)  returnElements.push(current);
        }
        return returnElements;
    }
}

8.addLoadEvent()

var addLoadEvent = function(fn) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = fn;
  }else {
    window.onload = function() {
      oldonload();
      fn();
    }
  }
}

9.addEvent()

function addEvent(elm, evType, fn, useCapture) {
  if (elm.addEventListener) {
    elm.addEventListener(evType, fn, useCapture);//DOM2.0
    return true;
  }
  else if (elm.attachEvent) {
    var r = elm.attachEvent('on' + evType, fn);//IE5+
    return r;
  }
  else {
    elm['on' + evType] = fn;//DOM 0
  }
}

javascript处理事件的一些兼容写法

绑定事件

var addEvent = function( obj, type, fn ) {
    if (obj.addEventListener)
        obj.addEventListener( type, fn, false );
    else if (obj.attachEvent) {
        obj["e"+type+fn] = fn;
        obj.attachEvent( "on"+type, function() {
            obj["e"+type+fn]();
        } );
    }
};

另一个实现

var addEvent = (function () { 
    if (document.addEventListener) { 
        return function (el, type, fn) { 
            el.addEventListener(type, fn, false); 
        }; 
    } else { 
        return function (el, type, fn) { 
            el.attachEvent('on' + type, function () { 
                return fn.call(el, window.event); 
            }); 
        } 
    } 
})();

绑定onpropertychange事件

onpropertychange是微软制造的一个事件,它在一个元素的属性发生变化的时候触发,常见的有文本的长度改变,样长改变等,FF大致和它相似的属性为oninput事件,不过它只针对textfield与textarea的value属性。safari,firefox,chrome与opera都支持此属性。

var addPropertyChangeEvent = function (obj,fn) {
    if(window.ActiveXObject){
        obj.onpropertychange = fn;
    }else{
        obj.addEventListener("input",fn,false);
    }
}

移除事件

var removeEvent = function( obj, type, fn ) {
    if (obj.removeEventListener)
        obj.removeEventListener( type, fn, false );
    else if (obj.detachEvent) {
        obj.detachEvent( "on"+type, obj["e"+type+fn] );
        obj["e"+type+fn] = null;
    }
};

加载事件

var loadEvent = function(fn) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = fn;
    }else {
        window.onload = function() {
            oldonload();
            fn();
        }
    }
}

阻止事件

var  stopEvent = function(e){
      e = e || window.event;
      if(e.preventDefault) {
        e.preventDefault();
        e.stopPropagation();
      }else{
        e.returnValue = false;
        e.cancelBubble = true;
      }
    }

如果仅仅是阻止事件冒泡

var stopPropagation = function(e) {
     e = e || window.event;
    if (!+"\v1") {
       e.cancelBubble = true;        
    } else {
       e.stopPropagation();
    }
}

取得事件源对象

相当于Prototype.js框架的Event.element(e)

var getEvent = function(e){
     e = e || window.event;
    return  event.target || event.srcElement
}
function getEvent() {
    if (window.event) return window.event;
    var c = getEvent.caller;
    while (c.caller) c = c.caller;
    return c.arguments[0];
} 

或者这个功能更强大,我在开发datagrid时开发出来的,详细用法见《一步步教你实现表格排序(第二部分)》。

var getEvent = function(e) {
  var e = e || window.event;
  if (!e) {
    var c = this.getEvent.caller;
    while (c) {
      e = c.arguments[0];
      if (e && (Event == e.constructor || MouseEvent  == e.constructor)) {
        break;
      }
      c = c.caller;
    }
  }
  var target = e.srcElement ? e.srcElement : e.target,
  currentN = target.nodeName.toLowerCase(),
  parentN  = target.parentNode.nodeName.toLowerCase(),
  grandN = target.parentNode.parentNode.nodeName.toLowerCase();
  return [e,target,currentN,parentN,grandN];
}

javascript 的forEach函数

在Base2中找到一个叫forEach的函数,是我见过的最好的实现。挖出来分析一下。它能对各种普通对象,字符串,数组以及类数组进行遍历。如果原游览器的对象已实现此函数,它则调用原对象的函数。

function forEach(object, block, context, fn) {
  if (object == null) return;
  if (!fn) {
    if (typeof object == "function" && object.call) {
      //遍历普通对象
      fn = Function;
    } else if (typeof object.forEach == "function" && object.forEach != arguments.callee) {
      //如果目标已经实现了forEach方法,则使用它自己的forEach方法(如标准游览器的Array对象)
      object.forEach(block, context);
      return;
    } else if (typeof object.length == "number") {
      // 如果是类数组对象或IE的数组对象
      _Array_forEach(object, block, context);
      return;
    }
  }
  _Function_forEach(fn || Object, object, block, context);
};
 
function _Array_forEach(array, block, context) {
  if (array == null) return;
  var i = 0,length = array.length;
  if (typeof array == "string") {
    for (; i < length; i++) {
      block.call(context, array.charAt(i), i, array);
    }
  }else{
    for (;i < length; i++) {
      block.call(context, array[i], i, array);
    }
  }
};
 
 
  _Function_forEach = function(fn, object, block, context) {
    // 这里的fn恒为Function
    for (var key in object) {
       //只遍历本地属性
       if (object.hasOwnProperty(key)) {
        //相当于  block(object[key], key)
        block.call(context, object[key], key, object);
      }
    }
  };

js深复制与浅复制

js深复制

var arr = [1,2,43];
var json = {a:6,b:4,c:[1,2,3]};
var str = 'sdfsdf';

var json2 = clone(json);

alert(json['c'])
function clone(obj){
    var oNew = new obj.constructor(obj.valueOf());
    if(obj.constructor == Object){
        for(var i in obj){
            oNew[i] = obj[i];
            if(typeof(oNew[i]) == 'object'){
                    clone(oNew[i]);
            }
        }
    }
    return oNew;
}