Javascript,Jquery笔记

  • 常用js函数(转载) 
    http://www.cnblogs.com/sicd/p/4310768.html
  • 事件处理 
    var EventUtil = {
           addHandler : function(element, type, handler){
                if(element.addEventListener){
                        element.addEventListener(type, handler, false);    
                }else if(element.attachEvent){
                         element.attachEvent("on"+type,handler);
                }else{
                         element["on"+type]=handler;
                }
           },
            removeHandler : function(element, type, handler){
                if(element.removeEventListener){
                      element.removeEventListener(type, handler, false);
               }else if(element.detachEvent){
                       element.detachEvent("on"+type, handler);
               }else{
                      element["on"+type]=null;
               }
           }
     } ;
     
  • 随机数
    rand = (function(){
      var today = new Date(); 
      var seed = today.getTime();
      function rnd(){
        seed = ( seed * 9301 + 49297 ) % 233280;
        return seed / ( 233280.0 );
      };
      return function rand(number){
        return Math.ceil(rnd(seed) * number);
      };
    })();
     
  •  window.console处理
    (function() {
        var method;
        var noop = function () {};
        var methods = [
            'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
            'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
            'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
            'timeStamp', 'trace', 'warn'
        ];
        var length = methods.length;
        var console = (window.console = window.console || {});
    
        while (length--) {
            method = methods[length];
    
            // Only stub undefined methods.
            if (!console[method]) {
                console[method] = noop;
            }
        }
    }());
     
  • $.ajax + Spring MVC
    $.ajax({
    	async : true , 
    	type : 'POST', 
    	url:'someurl', 
    	contentType: "application/json; charset=utf-8", //
    	processData:false, //To avoid making query String instead of JSON
    	data: JSON.stringify({}), //some parameters. Json Object.
    	success: function(data){
    	},
    	error: function(e){
    	}
    });
     
    @RequestMapping("/someurl")
    	public @ResponseBody Map<String, Object> someMethod(@RequestBody Map<String, Object> params){
    		//do sth.
    	}
     
  • window.location
    location = {  
        host: "localhost:8080",   
        hostname: "localhost",   
        href: "http://localhost:8080/webcontext/index.html",   
        origin: "http://localhost:8080",   
        pathname: "/webcontext/index.html",   
        port: "8080",   
        protocol: "http:",   
        reload: function reload() { [native code] },   
        replace: function () { [native code] },   
        ...  
    };  
    
    location.pathname = 'someUrl'; // 跳转到http://localhost:8080/someUrl
    location.href = 'someUrl'; //跳转到http://localhost:8080/webcontext/someUrl
    location.href = 'http://www.google.com'; //跳转到http://www.google.com
     
  • 实用技巧
    //随机数
    var MIN = 1, MAX=10;
    Math.floor(Math.random()*MAX); //  [0 , MAX)  ~~ 0-9
    Math.floor(Math.random()*(MAX-MIN+1)) + MIN; // [MIN, MAX] ~~ 1-10
    
    //随机字符串 [0-9a-z]+
    Math.random().toString(36).substr(2); //将随机小数转为36进制数并截去起始的'0.'
    
    //截去前后空格 trim
    String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, "") ;}
    
    //四舍五入
    3.1415926.toFixed(4); // 保留n位小数 3.1416
    3.1415925.toPrecision(4); //保留n位数字 3.142
    1234.1234.toPrecision(2); // 1.2e+3 
    
    //遍历属性
    for (var i in object) {
      if (object.hasOwnProperty(i)) { //避免访问到object.prototye的属性
        //do sth.
      }
    }
    
    // 遍历属性到数组
    var a = [];
    for (a[a.length] in obj); 
    // a[a.length]初始为undefined, 且a.length是不断增长的, 则随着循环,a[a.length]被依次赋值为obj的keys
    return a;
    
    //数组遍历. 不使用for in的方式来遍历数组
    for (var i=0, len=array.length; i < len; i++) {// i, len都只取值一次
      //do sth.
    }
     
递归
var array = [
  {id:1, pid:0, name:'node1', level:0},
  {id:2, pid:0, name:'node2', level:0},
  {id:3, pid:1, name:'node1-1', level:1},
  {id:4, pid:3, name:'node1-1-1', level:2},
  {id:5, pid:1, name:'node1-2', level:1},
  {id:6, pid:2, name:'node2-1', level:1},
  {id:7, pid:6, name:'node2-1-1', level:2},
];

//MAX LEVEL
var maxLevel = array.map(function(n){ return n.level }).reduce(function(pre, cur){ return pre > cur ? pre : cur });

// 递归
var root = { id : 0 , name : 'root' };
//(function(node){ //---> 匿名
(function addChilds(node) { //<--- 非匿名
  var childs = array.filter(function(n) { return n.pid == node.id });
  if (childs && childs.length > 0) {
    node.children = [];
    for (var i = 0, len = childs.length; i < len ; i++) {
      var child = childs[i];
      node.children.push(child);
      //arguments.callee(child); //---> 匿名
      addChilds(child); //<--- 非匿名
    }
  }
})(root);
/** ---JSON.stringify(root)---
{
    "id":0,
    "name":"root",
    "children":[
        {
            "id":1,
            "pid":0,
            "name":"node1",
            "level":0,
            "children":[
                {
                    "id":3,
                    "pid":1,
                    "name":"node1-1",
                    "level":1,
                    "children":[
                        {
                            "id":4,
                            "pid":3,
                            "name":"node1-1-1",
                            "level":2
                        }
                    ]
                },
                {
                    "id":5,
                    "pid":1,
                    "name":"node1-2",
                    "level":1
                }
            ]
        },
        {
            "id":2,
            "pid":0,
            "name":"node2",
            "level":0,
            "children":[
                {
                    "id":6,
                    "pid":2,
                    "name":"node2-1",
                    "level":1,
                    "children":[
                        {
                            "id":7,
                            "pid":6,
                            "name":"node2-1-1",
                            "level":2
                        }
                    ]
                }
            ]
        }
    ]
}
*/
 
  • 日期格式化
    var dateFormat = function (date, formatter) {
        date = date || new Date();
        formatter = formatter || "yyyy-MM-dd HH:mm:ss";
        
        var zeroize = function (value, length) {
            length = length || 2;
            value = new String(value);
            for (var i = 0, zeros = '', len = length - value.length; i < len; i ++) {
                zeros += '0';
            }
            return zeros + value;
        }
    
        var reg = /"[^"]*"|'[^']*'|\b(?:yy(?:yy)?|([MdHms])\1?|[S])\b/g;
        return formatter.replace(reg, function ($0) {
            switch ($0) {
            case 'd': return date.getDate();
    	case 'dd': return zeroize(date.getDate());
    	case 'M': return date.getMonth() + 1;
    	case 'MM': return zeroize(date.getMonth() + 1);
    	case 'yy': return new String(date.getFullYear()).substr(2);
    	case 'yyyy': return date.getFullYear();
    	case 'H': return date.getHours();
    	case 'HH': return zeroize(date.getHours());
    	case 'm': return date.getMinutes();
    	case 'mm': return zeroize(date.getMinutes());
    	case 's': return date.getSeconds();
    	case 'ss': return zeroize(date.getSeconds());	
    	case 'S': return zeroize(date.getMilliseconds(), 3);
            }
        });
    }
     
  • 序列化
    $.fn.serializeObject = function(){
        var o = {};
        var a = this.serializeArray();
        $.each(a, function() {
            if (o[this.name] !== undefined) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };
     
  • 类型判断
    $.isString = jQuery.fn.isString =function (/*anything*/it) {
    return (typeof it =="string"|| it instanceof String); // Boolean
     }
    
     $.isArray = jQuery.fn.isArray =function (/*anything*/it) {
    return it && (it instanceof Array ||typeof it =="array"); // Boolean
     }
    
     $.isFunction = jQuery.fn.isFunction =function (/*anything*/it) {
    return opts.call(it) ==="[object Function]";
     };
    
     $.isObject = jQuery.fn.isObject =function (/*anything*/it) {
    return it !== undefined &&
     (it ===null||typeof it =="object"|| $.isArray(it) || $.isFunction(it)); // Boolean
     }
    
     $.isArrayLike = jQuery.fn.isArrayLike =function (/*anything*/it) {
    return it && it !== undefined &&// Boolean
    !$.isString(it) &&!$.isFunction(it) &&
    !(it.tagName && it.tagName.toLowerCase() =='form') &&
     ($.isArray(it) || isFinite(it.length));
     }
     
  • outerHtml
    $.fn.outerHtml = function(){
    	return $("<p>").append(this.clone()).html();
    };
     
  • 表单清空
    $(':input','someFormSelector')  
    	.not(':button, :submit, :reset, :hidden')  
    	.val('')  
    	.removeAttr('checked')  
    	.removeAttr('selected');
     
  • console tips
    console.log("%c", "font-size:0;line-height:99px;padding:49px 50px;background:url(http://q1.qlogo.cn/g?b=qq&k=eT5IegWnWO37UVZhAPfatA&s=100) no-repeat");
    
    console.log("%chello%cworld%c!", "color:#0080FF", "color:#439C79", "color:#0080FF");
     
  • 在JS文件中引用外部JS文件
    document.write("<script language='javascript' src='someUrl/someScript.js' charset='utf-8'></script>");
    //注意charset!!
     
  • jquery.cookie.js(我写了半天还不如源码清晰明白, orZ)
    /*!
     * jQuery Cookie Plugin v1.4.0
     * https://github.com/carhartl/jquery-cookie
     *
     * Copyright 2013 Klaus Hartl
     * Released under the MIT license
     */
    (function (factory) {
    	if (typeof define === 'function' && define.amd) {
    		// AMD
    		define(['jquery'], factory);
    	} else if (typeof exports === 'object') {
    		// CommonJS
    		factory(require('jquery'));
    	} else {
    		// Browser globals
    		factory(jQuery);
    	}
    }(function ($) {
    
    	var pluses = /\+/g;
    
    	function encode(s) {
    		return config.raw ? s : encodeURIComponent(s);
    	}
    
    	function decode(s) {
    		return config.raw ? s : decodeURIComponent(s);
    	}
    
    	function stringifyCookieValue(value) {
    		return encode(config.json ? JSON.stringify(value) : String(value));
    	}
    
    	function parseCookieValue(s) {
    		if (s.indexOf('"') === 0) {
    			// This is a quoted cookie as according to RFC2068, unescape...
    			s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
    		}
    
    		try {
    			// Replace server-side written pluses with spaces.
    			// If we can't decode the cookie, ignore it, it's unusable.
    			// If we can't parse the cookie, ignore it, it's unusable.
    			s = decodeURIComponent(s.replace(pluses, ' '));
    			return config.json ? JSON.parse(s) : s;
    		} catch(e) {}
    	}
    
    	function read(s, converter) {
    		var value = config.raw ? s : parseCookieValue(s);
    		return $.isFunction(converter) ? converter(value) : value;
    	}
    
    	var config = $.cookie = function (key, value, options) {
    
    		// Write
    
    		if (value !== undefined && !$.isFunction(value)) {
    			options = $.extend({}, config.defaults, options);
    
    			if (typeof options.expires === 'number') {
    				var days = options.expires, t = options.expires = new Date();
    				t.setTime(+t + days * 864e+5);
    			}
    
    			return (document.cookie = [
    				encode(key), '=', stringifyCookieValue(value),
    				options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
    				options.path    ? '; path=' + options.path : '',
    				options.domain  ? '; domain=' + options.domain : '',
    				options.secure  ? '; secure' : ''
    			].join(''));
    		}
    
    		// Read
    
    		var result = key ? undefined : {};
    
    		// To prevent the for loop in the first place assign an empty array
    		// in case there are no cookies at all. Also prevents odd result when
    		// calling $.cookie().
    		var cookies = document.cookie ? document.cookie.split('; ') : [];
    
    		for (var i = 0, l = cookies.length; i < l; i++) {
    			var parts = cookies[i].split('=');
    			var name = decode(parts.shift());
    			var cookie = parts.join('=');
    
    			if (key && key === name) {
    				// If second argument (value) is a function it's a converter...
    				result = read(cookie, value);
    				break;
    			}
    
    			// Prevent storing a cookie that we couldn't decode.
    			if (!key && (cookie = read(cookie)) !== undefined) {
    				result[name] = cookie;
    			}
    		}
    
    		return result;
    	};
    
    	config.defaults = {};
    
    	$.removeCookie = function (key, options) {
    		if ($.cookie(key) === undefined) {
    			return false;
    		}
    
    		// Must not alter options, thus extending a fresh object...
    		$.cookie(key, '', $.extend({}, options, { expires: -1 }));
    		return !$.cookie(key);
    	};
    
    }));
     

相关推荐