轻设计 / 轻生活 / 轻日记 / 轻梦想 === zhoumojianshe ===
© 优特良品&优特建站出品 | Powered by YOUTIY
苏ICP备13018047号-1
jQuery 常用函数工具Util
TAGS: 前端设计

整理一下jQuery 常用函数工具Util,使用之前先引用

<script type="text/javascript" src="http://www.youtiy.com/pages/skin/js/jquery-1.8.2.min.js"></script>


	var BS_POST = function (action, data, isasync, callback) {
		jQuery.ajax({
			url: action,
			async: isasync,
			data: data,
			type: 'post',
			dataType: 'json',
			beforeSend: function () {
				//alert(action);
			},
			success: function (o) {
				// 可添加预处理
				//alert(o.status);
				if (callback && jQuery.isFunction(callback)) {
					callback(o);
				}
			},
			complete: function (XMLHttpRequest, textStatus) {
				//alert('ss2');
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				//alert(XMLHttpRequest.status);
				//alert(XMLHttpRequest.readyState);
				//alert(textStatus);
			}
		});
	};

	//==================cookie begin===========================
	var myDate = new Date();
	//设置cookie
	function setCookie(cname, cvalue, exdays) {
		var d = new Date();
		d.setTime(d.getTime() + (exdays*24*60*60*1000));
		var expires = "expires="+d.toUTCString();
		document.cookie = cname + "=" + cvalue + "; " + expires;
	}
	//获取cookie
	function getCookie(cname) {
		var name = cname + "=";
		var ca = document.cookie.split(';');
		for(var i=0; i<ca.length; i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1);
			if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
		}
		return "";
	}
	//清除cookie  
	function clearCookie(name) {  
		setCookie(name, "", -1);  
	}
	//==================cookie end===========================


	var base = function () {
		/** 添加到收藏夹 */
		function addfavorite(url, title) {
			try {
				window.external.AddToFavoritesBar(url, title); //IE7、IE8、IE9
			} catch (e) {
				try {
					window.external.addFavorite(url, title); //IE6  
				} catch (e) {
					try {
						window.sidebar.addPanel(title, url, title); //FireFox  
					} catch (e) {
						// Chrome
						base.yumAlert(property.favoriteBtn);
					}
				}
			}
		}

		/** form表单提交 */
		function setAction(action, method, formId, target) {
			action = requestContextPath + "/" + action;
			method = method || "post";
			formId = "#" + (formId || "mainForm");
			target = target || "_self";
			$(formId).attr("action", action).attr("method", method).attr("target", target).submit();
		}

		function yumAlert(text) {
			alert(333);
			$("#dialog-message-alert span").html(text);
			//alert(333);
			$("#dialog-message-alert").dialog({
				resizable: false,
				minHeight: '96px',
				modal: true,
				closeOnEscape: true,
				dialogClass: "ui-alert",
				position: {
					my: "center",
					at: "center",
					of: window,
					collision: "fit"
				},
				buttons: {
					base_confirm: function () {
						$(this).dialog("close");
					}
				}
			});
		}

		function yumAlertBack(text, callback) {
			$("#dialog-message-alert-back span").html(text);
			$("#dialog-message-alert-back").dialog({
				resizable: false,
				minHeight: '96px',
				modal: true,
				closeOnEscape: false,
				dialogClass: "ui-alert",
				position: {
					my: "center",
					at: "center",
					of: window,
					collision: "fit"
				},
				buttons: {
					base_confirm: function () {
						$(this).dialog("close");
						callback.call(); // 回调
					}
				}
			});
		}

	  

		function yumConfirm(text, callback1, callback2) {
			$("#dialog-message-confirm span").html(text);
			$("#dialog-message-confirm").dialog({
				resizable: false,
				minHeight: '96px',
				modal: true,
				closeOnEscape: true,
				dialogClass: "ui-alert",
				position: {
					my: "center",
					at: "center",
					of: window,
					collision: "fit"
				},
				buttons: {
					base_confirm: function () {
						$(this).dialog("close");
						if (callback1) {
							callback1.call(); // 回调
						}
					},
					base_cancle: function () {
						$(this).dialog("close");
						if (callback2) {
							callback2.call(); // 回调
						}
					}
				}
			});
			$('[role="dialog"]').css('left', ($(window).width() - 
                        $('[role="dialog"]').width()) / 2 + 'px');
		}

		function openloading() {

			$("#dialog-loading").dialog({
				resizable: false,
				minHeight: '96px',
				title: "",
				//dialogClass:"ui-alert",
				modal: true

			});
		}

		function closeLoading() {
			$("#dialog-loading").dialog("close");
		}


		return {
			yumAlert: function (text) { yumAlert(text); },
			yumAlertBack: function (text, callback) { yumAlertBack(text, callback); },
			yumConfirm: function (text, callback1, callback2) 
                        { yumConfirm(text, callback1, callback2); },
			yumOpenLoading: function () { openloading(); },	
			yumCloseLoading: function () { closeLoading(); },
			setAction: function (action, method, formId, target) 
                        { setAction(action, method, formId, target); },
			addFavorite: function () { addFavorite(); },
		};
	}();







	jQuery.extend({
		trimD: function (str) {
			if (null == str) {
				return str;
			}
			return str.replace(/^D(B|N)?/, '');
		},

		/** 根据当前浏览器言语,提供相关数据的中英文版本*/
		localStr: function (data, trimFlag) {
			if (locale == 'en_US') {
				if (trimFlag == 1) {
					return data.en;
				}
				return data.en;
			} else if (locale == 'zh_CN') {
				if (trimFlag == 1) {
					return $.trimD(data.cn);
				}
				return data.cn;

			}
		},
		isEnglish: function () {
			if (locale == 'en_US') {
				return true;
			}
			return false;
		},
		moneyFormat: function (data) {
			if ($.isEnglish()) {
				data = pageMessage.yun + data;
			} else {
				data = data + pageMessage.yun;
			}
			return data;
		},
		
		/**
		 * @decription 给方法添加加载函数
		 * @param t : string 加载文字
		 * @param w : string 加载框宽度
		 * @param h : string 加载框高度
		 */
		showLoading: function (t, w, h) { //显示加载
			$body = $('body');
			var content="";
			// content="<div class=\"zzsc1\">"+
						  // "<div class=\"rect1\"></div>"+
						  // "<div class=\"rect2\"></div>"+
						  // "<div class=\"rect3\"></div>"+
						  // "<div class=\"rect4\"></div>"+
						  // "<div class=\"rect5\"></div>"+
						// "</div>";
			//content="<div class=\"zzsc2\"></div>";
			//content="<div class=\"zzsc7\"></div>";
			content="<div class=\"zzsc6\">"+
					  "<div class=\"bounce1\"></div>"+
					  "<div class=\"bounce2\"></div>"+
					  "<div class=\"bounce3\"></div>"+
					"</div>";
			t = t != undefined ? t : content;
			w = w != undefined ? parseInt(w) : '90';
			h = h != undefined ? parseInt(h) : '250';
			var margin = ""+(-(h/2))+'px 0 0 '+(-(w/2))+"px";
			$body.stop().append('<div id="HLoading" 
                        style="width:'+w+'px;height:'+h+'px;line-height:'+h+'px;
                        text-align:center;position:fixed;top:30%;
                        left:50%;margin:'+margin+';">'+t+'</div>');
			//$body.stop().append('<div id="HLoading" 
                       style="width:'+w+'px;height:'+h+'px;
                       line-height:'+h+'px;background:rgba(0,0,0,0.6);
                       color:#fff;text-align:center;
                       position:fixed;top:50%;left:50%;margin:'+margin+';">'+t+'</div>');
		},
		removeLoading:function(){
			$("#HLoading").hide();
		},
		showOverlay:function(){
			$body = jQuery('body');
			var div="<div id=\"overlay\" 
                        style=\"background-color:black;position:absolute;top:0px;
                        left:0px;width:500px;height:500px;filter:Alpha(opacity=30);
                        opacity:0.3;z-index:10000\"></div>";
			$body.stop().append(div);
			jQuery("#overlay").height(document.body.scrollHeight);
			jQuery("#overlay").width(document.body.scrollWidth);

			// fadeTo第一个参数为速度,第二个为透明度
			// 多重方式控制透明度,保证兼容性,但也带来修改麻烦的问题
			jQuery("#overlay").fadeTo(200, 0.5);
			jQuery(window).scroll(function(){
					jQuery("#overlay").height(document.body.scrollHeight);
					jQuery("#overlay").width(document.body.scrollWidth);
				}
			);
			
			jQuery(window).resize(function(){
					jQuery("#overlay").height(document.body.scrollHeight);
					jQuery("#overlay").width(document.body.scrollWidth);
			});
		},
		hideOverlay:function(){
			jQuery("#overlay").fadeOut(200);
		}
	});

	/**
	 * 共通js
	 */
	var common = function () {
		/** 邮件 */
		var email = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
		/** 手机号 */
		var strArray = [// 移动
						'139', '138', '137', '136', '135', '134', '147', '150', '151', 
            '152', '157', '158', '159', '178', '182', '183', '184', '187', '188',
						// 联通
						'130', '131', '132', '155', '156', '185', '186', '145', '176',
						// 电信
						'133', '153', '177', '180', '181', '189',
						// 京东通信
						'170'];
		var mobile = new RegExp('^(' + strArray.join('|') + ')\\d{8}$');
		/** 区号 */
		var areaCode = /^\d{3,4}$/;
		/** 固定电话号码 */
		var telphone = /^\d{7,8}$/;
		/** 数字 */
		var number = /^[0-9]*[1-9][0-9]*$/;//正整数 
		/** 一个数字 */
		var num = /[0-9]/;

		/** 字符串校验规则1 - 判断普通输入框是否为特殊字符*/
		var vaildStr1 = new Array("<script>", "script", "src", "select", "update",
							"delete", "insert", "<", ">", "%", "&", ":", "'", "\"",
							"style", "<!--**-->", "/**", "//**", " **/", "--**",
							"/n*", "/t*", "*.*", "|", "$");

		/** 字符串校验规则2 - 判断姓名是否为特殊字符*/
		var vaildStr2 = new Array("<script>", "script", "src", "select",
							"update", "delete", "insert", "<", ">", "style",
							"%", "&", ":", "|", "'", "/", "\"", "!",
							"%", "”", "“", "﹛", "﹚", "﹙", "﹜", "+", "[", "]", "!", "@", "?",
							"#", "%", "……", "*", "(", ")", "{", "}", "《", "》", "?", ",", "。",
							"$", "(", ")",
							"<!--**-->", "/**", "//**", " **/", "--**",
							"/n*", "/t*", "*.*", "|", "$");

		var validStr3 = new Array("|", "$", "<", ">", "+", "script", "src", "select", "update",
				"delete", "insert", "style", "<!--**-->", "/**", "//**", " **/", "--**",
				"/n*", "/t*", "*.*");

		//var str = /^[0-9a-zA-Z\,\$\^\(\)\-\_\+\[\]\{\}\u4e00-\u9fa5]{1,20}$/;

		var str = /^[0-9a-zA-Z\.\-\_\u4e00-\u9fa5]{1,24}$/;


		/**
		 * 校验字符串
		 * @param value 待校验的字符串
		 * @param type  校验格式类型,1:判断普通输入框是否为特殊字符
		 * 						    2:判断姓名是否为特殊字符  
		 * @return true 校验不通过,true 校验不通过 false 校验通过
		 */
		function isStr2(value, type) {
			var arr = validStr3;
			//		if (type == 1){
			//			arr = vaildStr1;
			//		}else if (type == 2){
			//			arr = vaildStr2;
			//		}else if (type == 3){
			//			arr = validStr3;
			//		}

			var bool = false;
			for (var i = 0; i < arr.length; i++) {
				if (value.indexOf(arr[i]) >= 0) {
					bool = true;
					break;
				}
			}

			return bool;
		}

		function isStr(value) {
			return str.test($.trim(value));
		}



		function isEmail(value) {
			return email.test($.trim(value));
		}

		function isMobile(value) {
			return mobile.test($.trim(value));
		}

		function isAreaCode(value) {
			return areaCode.test($.trim(value));
		}

		function isTelephone(value) {
			return telphone.test($.trim(value));
		}

		function isNumber(value) {
			return number.test($.trim(value));
		}

		function isNum(value) {
			return num.test($.trim(value));
		}

		return {
			isEmail: function (value) { return isEmail(value); },
			isMobile: function (value) { return isMobile(value); },
			isAreaCode: function (value) { return isAreaCode(value); },
			isTelephone: function (value) { return isTelephone(value); },
			isNumber: function (value) { return isNumber(value); },
			isNum: function (value) { return isNum(value); },
			isStr: function (value) { return isStr(value); },
			isStr2: function (value, type) { return isStr2(value, type); }
		};
	}();

	/** 相关配置 */
	var yumCfg = {
		// 
		sid: "yum_sid",
		// 登录“记住我”功能
		rememberUser: "yum_ueserInfo",
		// "谢谢,我不需要"功能
		myNotNeed: "yum_myNotNeed",
		// 订单确认页面标示
		orderFlag: "yum_order",
		// 支付页面标示
		payFlag: "yum_pay",
		// 记住我功能的有效期(天)
		keep: 7,
		// 餐厅状态
		STORE_STATUS_NOTOPEN: "0",
		STORE_STATUS_NORMAL: "1",
		STORE_STATUS_CLOSE: "2",
		STORE_STATUS_TEMPCLOSE: "3"
	};


	/** 添加String的format方法
	 *  替换对应位置的字符串
	 *  @param array[] 数组
	 */
	String.prototype.format = function (array) {
		return this.replace(/\{(\d+)\}/g, function (s, i) {
			return array[i];
		});
	};



	//生成GUID
	function newGuid() {
		var guid = "";
		for (var i = 1; i <= 32; i++) {
			var n = Math.floor(Math.random() * 16.0).toString(16);
			guid += n;
			if ((i == 8) || (i == 12) || (i == 16) || (i == 20))
				guid += "-";
		}
		return guid;
	}


	//判断浏览器类型
	function showBrowser() {

		if (navigator.userAgent.indexOf("Opera") >= 0) {
			return "opera";
		} else {

			if (navigator.userAgent.indexOf("360SE") >= 0) {
				return "360";
			} else {

				if (navigator.userAgent.indexOf("SE") >= 0) {
					return "sougou";
				}

				else {

					if (navigator.userAgent.indexOf("Firefox") >= 0) {
						return "firefox";
					} else {

						if (navigator.userAgent.indexOf("Chrome") >= 0) {
							return "chrome";
						} else {
							if (maxthonVersion() != "false") {
								return "maxthon";
							}

							else {

								if (navigator.userAgent.indexOf("TencentTraveler") >= 0) {
									return "txtt";
								}

								else {

									if (navigator.userAgent.indexOf("Safari") >= 0) {
										return "safari";
									} else {

										if (navigator.userAgent.indexOf('Netscape') >= 0) {
											return "netscape";
										} else {

											return "ie";
										}
									}
								}
							}
						}
					}
				}

			}
		}
	}

	function isMaxthon() {
		try {
			window.external.max_invoke("GetHotKey");
			return true;
		} catch (ex) {
			return false;
		}
	}

	function maxthonVersion() {
		if (isMaxthon()) {
			if (window.external && window.external.max_version) {
				return window.external.max_version.substr(0, 1);
			}
			return "false";
		} else {
			return "false";
		}

	}



	$.serializeObject = function (form) {
		var o = {};
		$.each(form.serializeArray(), function (index) {
			if (o[this['name']]) {
				o[this['name']] = o[this['name']] + "," + this['value'];
			} else {
				o[this['name']] = this['value'];
			}
		});
		return o;
	};


	function IsPC() {
				var userAgentInfo = navigator.userAgent;
				var Agents = ["Android", "iPhone",
							"SymbianOS", "Windows Phone",
							"iPad", "iPod"];
				var flag = true;
				for (var v = 0; v < Agents.length; v++) {
					if (userAgentInfo.indexOf(Agents[v]) > 0) {
						flag = false;
						break;
					}
				}
				return flag;
	}

	//全站统一URL
	var baseUrl="http://localhost:8087";


也可以直接引用:

<script type="text/javascript" src="http://www.youtiy.com/pages/skin/js/base.js"></script>

周末
2021-11-26 08:55:34
标签云
网页设计 精致慢生活 感悟思语 我的旧年华
加偶微信