tools.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. (function(mod) {
  2. if (typeof exports == "object" && typeof module == "object") // CommonJS 规范
  3. module.exports = mod;
  4. else if (typeof define == "function" && define.amd) // AMD 规范
  5. return define(['jquery','jquery.validate'], mod);
  6. else // Plain browser env 浏览器
  7. this.tools = mod();
  8. })(function() {
  9. var tools = {};
  10. tools.check_cookie = function(){
  11. if(window.navigator.cookieEnabled)
  12. return true;
  13. else{
  14. alert("浏览器配置错误,Cookie不可用!");
  15. return false;
  16. }
  17. };
  18. tools.set_cookie = function(name,value){
  19. var Days = 30; //此 cookie 将被保存 30 天
  20. var exp = new Date(); //new Date("December 31, 9998");
  21. exp.setTime(exp.getTime() + Days*24*60*60*1000);
  22. document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
  23. };
  24. tools.get_cookie = function(name)
  25. {
  26. var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
  27. if(arr !== null){
  28. return unescape(arr[2]);
  29. }else{
  30. return null;
  31. }
  32. // var regexp = new RegExp("(?:^" + name + "|;\s*"+ name + ")=(.*?)(?:;|$)", "g");
  33. // var result = regexp.exec(document.cookie);
  34. // return (result === null) ? null : result[1];
  35. };
  36. tools.del_cookie = function(name)
  37. {
  38. var exp = new Date();
  39. exp.setTime(exp.getTime() - 1);
  40. var cval=getCookie(name);
  41. if(cval!==null){
  42. document.cookie= name + "="+cval+";expires="+exp.toGMTString();
  43. }
  44. };
  45. // 检测空对象
  46. // 空则返回true
  47. tools.isEmptyValue = function(value) {
  48. var type;
  49. if(value === null) { // 等同于 value === undefined || value === null
  50. return true;
  51. }
  52. type = Object.prototype.toString.call(value).slice(8, -1);
  53. switch(type) {
  54. case 'String':
  55. return !!$.trim(value);
  56. case 'Array':
  57. return !value.length;
  58. case 'Object':
  59. // return $.isEmptyObject(value);
  60. return !value.length;
  61. default:
  62. return false;
  63. }
  64. };
  65. tools.isEmpty = function(v){
  66. if (v instanceof String) {
  67. var r = /^\s*$/;
  68. return r.test(v);
  69. }else if(v instanceof Array){
  70. return !v.length;
  71. }else if(v instanceof Object){
  72. return v === {};
  73. }else{
  74. return false;
  75. }
  76. };
  77. tools.is_set = function(value){
  78. if (typeof(value) == "undefined") {
  79. return false;
  80. }else{
  81. return true;
  82. }
  83. };
  84. // 解析URL路径
  85. tools.parseURL = function(url) {
  86. var a = document.createElement('a');
  87. a.href = url;
  88. return {
  89. source: url,
  90. protocol: a.protocol.replace(':',''),
  91. host: a.hostname,
  92. port: a.port,
  93. query: a.search,
  94. params: (function(){
  95. var ret = [],
  96. seg = a.search.replace(/^\?/,'').split('&'),
  97. len = seg.length, i = 0, s;
  98. for (;i<len;i++) {
  99. if (!seg[i]) { continue; }
  100. s = seg[i].split('=');
  101. ret[i] = {"key":s[0],"val":s[1]};
  102. }
  103. return ret;
  104. })(),
  105. file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],
  106. hash: a.hash.replace('#',''),
  107. path: a.pathname.replace(/^([^\/])/,'/$1'),
  108. relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],
  109. segments: a.pathname.replace(/^\//,'').split('/')
  110. };
  111. };
  112. // TODO: url params change
  113. tools.imgReady = (function () {
  114. var list = [];
  115. var intervalId = null;
  116. // 用来执行队列
  117. var tick = function () {
  118. var i = 0;
  119. for (; i < list.length; i++) {
  120. list[i].end ? list.splice(i--, 1) : list[i]();
  121. }
  122. !list.length && stop();
  123. };
  124. // 停止所有定时器队列
  125. var stop = function () {
  126. clearInterval(intervalId);
  127. intervalId = null;
  128. };
  129. return function (url, ready, load, error) {
  130. var onready, width, height, newWidth, newHeight,
  131. img = new Image();
  132. img.src = url;
  133. // 如果图片被缓存,则直接返回缓存数据
  134. if (img.complete) {
  135. ready.call(img);
  136. load && load.call(img);
  137. return;
  138. }
  139. width = img.width;
  140. height = img.height;
  141. // 加载错误后的事件
  142. img.onerror = function () {
  143. error && error.call(img);
  144. onready.end = true;
  145. img = img.onload = img.onerror = null;
  146. };
  147. // 图片尺寸就绪
  148. onready = function () {
  149. newWidth = img.width;
  150. newHeight = img.height;
  151. if (newWidth !== width || newHeight !== height ||
  152. // 如果图片已经在其他地方加载可使用面积检测
  153. newWidth * newHeight > 1024
  154. ) {
  155. ready.call(img);
  156. onready.end = true;
  157. }
  158. };
  159. onready();
  160. // 完全加载完毕的事件
  161. img.onload = function () {
  162. // onload在定时器时间差范围内可能比onready快
  163. // 这里进行检查并保证onready优先执行
  164. !onready.end && onready();
  165. load && load.call(img);
  166. // IE gif动画会循环执行onload,置空onload即可
  167. img = img.onload = img.onerror = null;
  168. };
  169. // 加入队列中定期执行
  170. if (!onready.end) {
  171. list.push(onready);
  172. // 无论何时只允许出现一个定时器,减少浏览器性能损耗
  173. if (intervalId === null) intervalId = setInterval(tick, 40);
  174. };
  175. };
  176. })();
  177. // 一部加载页面对分页按钮处理 ,id 带有 #
  178. tools.load_page = function(_url,nodeId) {
  179. var _load_page = function(__url){
  180. $.ajax({
  181. url: __url,
  182. type: 'GET',
  183. dataType: 'html'
  184. })
  185. .done(function(data) {
  186. console.log("success");
  187. $(nodeId).html(data);
  188. $(nodeId+" .pagination a").each(function(index, el) {
  189. var elhref = $(el).attr('href');
  190. if ( elhref == '#' ) {
  191. elhref = __url;
  192. $(el).attr('data-href',__url);
  193. }else{
  194. $(el).attr('data-href',elhref);
  195. }
  196. $(el).attr('href','javascript:void(0)');
  197. // $(el).attr('href',"javascript:tools.load_page('"+elhref+"','"+nodeId+"')");
  198. });
  199. })
  200. .fail(function() {
  201. console.log("error");
  202. })
  203. .always(function() {
  204. console.log("complete");
  205. });
  206. };
  207. _load_page(_url);
  208. $(nodeId).delegate('a[data-href]','click',function(){
  209. _load_page($(this).attr('data-href'));
  210. });
  211. };
  212. /**
  213. * @brief 创建表单验证
  214. * 注意引用 jquery.validate.js 和 jquery.validate.lang.cn.js
  215. * @param frm 表单 Id
  216. * @param rules 验证规则
  217. */
  218. tools.make_validate = function(frm,rules,messages,inline){
  219. if (inline === 0) {
  220. inline = "block";
  221. }else{
  222. inline = "inline";
  223. }
  224. $('#'+frm).validate({
  225. ignore: ".ignore", // 忽略
  226. rules:rules,
  227. onchange: true,
  228. onblur: true,
  229. messages:messages,
  230. errorClass: "help-"+inline+" validate",
  231. errorElement: "span",
  232. highlight:function(element, errorClass, validClass) {
  233. $(element).parents('.control-group').removeClass('success').addClass('error');
  234. $(element).removeClass('success').addClass('error');
  235. $(element).nextAll('span.validate').remove();
  236. },
  237. unhighlight: function(element, errorClass, validClass) {
  238. $(element).parents('.control-group').removeClass('error').addClass('success');
  239. $(element).removeClass('error').addClass('success');
  240. $(element).nextAll('span.validate').remove();
  241. },
  242. errorPlacement: function(error, element) {
  243. if (inline == "block") {
  244. error.appendTo(element.parents(".control-group"));
  245. }else{
  246. element.after(error);
  247. }
  248. }
  249. });
  250. };
  251. /**
  252. * @brief 创建表单验证
  253. 带有返回函数, 可以验证后直接用ajax处理
  254. * 注意引用 jquery.validate.js 和 jquery.validate.lang.cn.js
  255. * @param frm 表单 Id
  256. * @param rules 验证规则
  257. */
  258. tools.make_validate_submit = function(frm,rules,messages,submit_fun,inline){
  259. if (inline === 0) {
  260. inline = "block";
  261. }else{
  262. inline = "inline";
  263. }
  264. $('#'+frm).validate({
  265. ignore: ".ignore", // 忽略
  266. rules:rules,
  267. onchange: true,
  268. onblur: true,
  269. messages:messages,
  270. errorClass: "help-inline validate",
  271. errorElement: "span",
  272. highlight:function(element, errorClass, validClass) {
  273. $(element).parents('.control-group').removeClass('success').addClass('error');
  274. $(element).removeClass('success').addClass('error');
  275. $(element).nextAll('span.validate').remove();
  276. },
  277. unhighlight: function(element, errorClass, validClass) {
  278. $(element).parents('.control-group').removeClass('error').addClass('success');
  279. $(element).removeClass('error').addClass('success');
  280. $(element).nextAll('span.validate').remove();
  281. },
  282. errorPlacement: function(error, element) {
  283. if (inline == "block") {
  284. error.appendTo(element.parents(".control-group"));
  285. }else{
  286. element.after(error);
  287. }
  288. },
  289. submitHandler:function(form){
  290. submit_fun(form);
  291. }
  292. });
  293. };
  294. return tools;
  295. });