自己用的javascript 共用函数

/**
 * 返回數組某個值的下標
 * 
 */
Array.prototype.position = function(val){
    for(var i in this){
         if(this[i]==val){
             return i;
             break;
         }
    }
    return -1;
}


/**
*刪除數組中某個值
*
*/
Array.prototype.remove_value = function(val) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] == val) {
      this.splice(i, 1);
      break;
    }
  }
}


/**
 * 判斷數組是否存在某個值
 * 
 */
Array.prototype.in_array=function(val){
    this.S = String.fromCharCode(2);
    var r = new RegExp(this.S + val + this.S);
    return (r.test(this.S + this.join(this.S) + this.S));
}


/**
 * 数组去重复
 * 
 */
Array.prototype.array_unique = function(){
    
    var m,n = [],o= {};
    for (var i = 0; (m = this[i]) !== undefined; i++){
        if (!o[m]){
            n.push(m);
            o[m] = true;
        }
    }
    return n;
}

/**
 *刪除字符串的空格換行符囘車符 
 *
 */
String.prototype.trim = function(){
    
    return this.replace(/(\ +)|([ ])|([\r\n])/g, "");
}

String.prototype.is_email = function(){

    var reg = /^[A-Za-z\d]+([-_\.\+]*[A-Za-z\d])*@([A-Za-z\d-]{0,61}[A-Za-z\d]\.)+[A-Za-z\d]{2,6}$/;
    return reg.test(this);
}


/**
 * 判斷是否為數組 不包括對象
 * 很好解決跨 iframe 判斷是的問題
 */
function is_array(obj){
    
    return Object.prototype.toString.call(obj) === '[object Array]';
}

//判断是否为空
function is_empty(str){
    if(str==null || typeof str=="undefined" || str.trim()==""){
        return true;
    }else{
        return false;
    }
} 

//添加收藏夹
function add_favorite() {
    var title = "收藏", url = 'http://www.baidu.com';
    try {
        window.external.AddFavorite(url, title);
    }
    catch(e){
        try {
            window.sidebar.addPanel(title, url, "");
        } catch (e) {
            alert("您使用的浏览器暂不支持此功能,请自行加入收藏。");
        }
    }
    addCtpv(100, "AddFavorite");
}


//复制到剪贴板
function copy_to_clipboard(txt) {
    if (window.clipboardData) {
        window.clipboardData.clearData();
        window.clipboardData.setData("Text", txt);
    } else if (navigator.userAgent.indexOf("Opera") != -1) {
        window.location = txt;
    } else if (window.netscape) {
        try {
            netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
        } catch (e) {
            alert("被浏览器拒绝!\n请在浏览器地址栏输入'about:config'并回车\n然后将'signed.applets.codebase_principal_support'设置为'true'");
        }
        var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
        if (!clip)
            return;
        var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
        if (!trans)
            return;
        trans.addDataFlavor('text/unicode');
        var str = new Object();
        var len = new Object();
        var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
        var copytext = txt;
        str.data = copytext;
        trans.setTransferData("text/unicode", str, copytext.length * 2);
        var clipid = Components.interfaces.nsIClipboard;
        if (!clip)
            return false;
        clip.setData(trans, null, clipid.kGlobalClipboard);
        alert("复制成功!")
    }
}

/**
 * 讀取COOKIE
 */
function get_cookie(name){ 
    var arg = decodeURIComponent(name) + "="; 
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    var endstr = null;
    
    while (i < clen) {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg){
            endstr = document.cookie.indexOf (";", j);
            if (endstr == -1) endstr = document.cookie.length;
            return decodeURIComponent(document.cookie.substring(j, endstr));
        }
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break; 
    } 
    return null;
}


/**
 * 设置COOKIE expires 分鐘
 */
function set_cookie(name, value){
    var argv = set_cookie.arguments;
    var argc = set_cookie.arguments.length;
    var expires = (argc > 2) ? argv[2] : null;
    var path = (argc > 3) ? argv[3] : null;
    var domain = (argc > 4) ? argv[4] : null;
    var secure = (argc > 5) ? argv[5] : false;
    
    if(expires){
        var exp = new Date();
        exp.setTime(exp.getTime() + expires*60*1000);
        expires = exp;
    }
    
    document.cookie = encodeURIComponent(name) + "=" + encodeURIComponent (value) 
        + ((expires == null) ? "" : ("; expires=" + expires))
        + ((path == null) ? "" : ("; path=" + path)) 
        + ((domain == null) ? "" : ("; domain=" + domain))
        + ((secure == true) ? "; secure" : "");
}


/**
 * 刪除COOKIE 
 */
function delete_cookie(name){ 
    var exp = new Date(); 
    exp.setTime (exp.getTime() - 1);
    var cval = 0;
    document.cookie = encodeURIComponent(name) + "=" + cval + "; expires=" + exp.toGMTString();
}


/**
 * 出loading message 兼容IE
 * @param message 等於false 則隱藏
 * @param overlay false 不出遮罩層
 * 
 */
function loading_message(message, overlay){

    $("#show_loading_message_container,#show_loading_message_layer").remove();
    if(message !== false){
        var div_html = '';
        if(overlay !== false){//overlayer設置
            div_html = '<div id="show_loading_message_layer" style="position:fixed;left:0;top:0;z-index:99998;background:#ddd;width:'+$(document).width()+'px;height:'+$(document).height()+'px"></div>';
        }
         div_html += '<div id="show_loading_message_container" style="overflow:hidden;background: #333;width: 269px;height: 107px;position: absolute;left: -1000px;top: -1000px;text-align: center;">';
         div_html += '<span style="color: #FFF;line-height: 107px;font-size: 23px; white-space: nowrap;">&nbsp;&nbsp;';
         div_html += '<img src="style/images/load.gif" style="vertical-align: middle;"/>&nbsp;&nbsp;'+message+'</span></div>';
        
        var $div = $(div_html);
        var $container = overlay !== false ? $div.eq(0).css('opacity', 0.30).siblings('#show_loading_message_container') : $div;
        
        $("body").append($div);
        $container.css({zIndex:99999, left:parseInt(($(window).width()-$container.width())/2), top:parseInt($(window).scrollTop()+($(window).height()-$container.height())/2)});
        
        $(window).on('resize', function(){
            $("#show_loading_message_layer").hide().css({width:$(document).width()+'px', height:$(document).height()+'px'}).show();//先隱藏之前的取到真實的
            var $message_container = $("#show_loading_message_container");
            $message_container.css({left:parseInt(($(window).width()-$message_container.width())/2), top:parseInt($(window).scrollTop()+($(window).height()-$message_container.height())/2)});
        });
        
    }
    
}



/**
* check_uncheck 全選; 反選,單一反選去全選, 滿單選選全選
* 指定 checkedall 的checkbox checkedall='true'
* $.check_uncheck(checkbox_name);
*/
jQuery.check_uncheck = function(checkbox_name){

    var $checkbox = $("input[name='"+checkbox_name+"']");//要操作的 checkbox 的對象包括了全選的checkbox
    var $checkallobj = $checkbox.filter("input[checkedall='true']").eq(0);//全選的checkbox
    
    $checkbox.on("click", function(){
        if($(this).is(":checked")){
            if($(this).is($checkallobj)){
                $checkbox.attr("checked", "checked");
            }else{
                if($checkbox.filter(":checked").length + 1 >= $checkbox.length){
                    $checkallobj.attr("checked", "checked");
                }
            }
        }else{
            if($(this).is($checkallobj)){
                $checkbox.removeAttr("checked");
            }else{
                $checkallobj.removeAttr("checked");
            }
        }
    });
    
};


//對象級的函數
/* show_message
 * _position_flag={left: '+100', top: '-100'}信息提示 位置適合于任何坐標 false的時候則根據當前對象取坐標,不填則中間位置
 */
(function($){
    $.fn.show_message = function (_message, _position_flag, _times){
        
        var $this = $(this), sm_top = 0, sm_left = 0;
        
        if($this && (typeof(_position_flag) === "object") || _position_flag === false){
            
            var setting = {left: '+0', top: '-0'};
            //    /(\+|\-)\s*\d+/
            $.extend(setting, _position_flag);
            sm_top = parseInt( eval( $this.offset().top + setting.top )); 
            sm_left = parseInt( eval( $this.offset().left + setting.left ));

        }else{
            
            sm_top = $(window).height()/2; 
            sm_left = $(window).width()/2;
            
        }
        
        var $message_obj = $('<span id="show_msg_tips" style="background:#FCE08E;border:1px solid #FF9933;color:#4B4B93;display:none;font-size:13px;font-weight:bold;line-height:25px;max-width:380px; min-width:200px;padding:8px;position:fixed;z-index:99999;">'+ _message +'</span>');
        
        $("#show_msg_tips").remove();
        $message_obj.appendTo('body').show().css({left:sm_left-$message_obj.width()/2, top:sm_top-$message_obj.height()/2});
        
        setTimeout(function(){
            $message_obj.fadeOut(1000);
        }, _times ? _times : 1800);
    
    }
    
})(jQuery);


/**兼容性
 * //绑定事件 window onload
  var addEvent = document.addEventListener ? function(el,type,callback){
    el.addEventListener( type, callback, !1 );
  } : function(el,type,callback){
    el.attachEvent( "on" + type, callback );
  }
  //移除事件
  var removeEvent = document.removeEventListener ? function(el,type,callback){
    el.removeEventListener( type, callback );
  } : function(el,type,callback){
    el.detachEvent( "on" + type, callback);
  }
  
  removeEvent(document,"mousemove",function);
 */

 

posted @ 2014-06-24 23:22  timily  阅读(248)  评论(0编辑  收藏  举报