知识点积累

JS判断是否是手机客户端

 1 var isMobile = {
 2     Android: function () {
 3         return navigator.userAgent.match(/Android/i) != null;
 4     },
 5     BlackBerry: function () {
 6         return navigator.userAgent.match(/BlackBerry/i) != null;
 7     },
 8     iOS: function () {
 9         return navigator.userAgent.match(/iPhone|iPad|iPod/i) != null;
10     },
11     Opera: function () {
12         return navigator.userAgent.match(/Opera Mini/i) != null;
13     },
14     Windows: function () {
15         return navigator.userAgent.match(/IEMobile/i) != null;
16     },
17     Any: function () {
18         return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());  
19     }
20 };

 解析URL各部分的通用方法

 1 function parseURL(url) {
 2     var a =  document.createElement('a');
 3     a.href = url;
 4     return {
 5         source: url,
 6         protocol: a.protocol.replace(':',''),
 7         host: a.hostname,
 8         port: a.port,
 9         query: a.search,
10         params: (function(){
11             var ret = {},
12                 seg = a.search.replace(/^\?/,'').split('&'),
13                 len = seg.length, i = 0, s;
14             for (;i<len;i++) {
15                 if (!seg[i]) { continue; }
16                 s = seg[i].split('=');
17                 ret[s[0]] = s[1];
18             }
19             return ret;
20         })(),
21         file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],
22         hash: a.hash.replace('#',''),
23         path: a.pathname.replace(/^([^\/])/,'/$1'),
24         relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],
25         segments: a.pathname.replace(/^\//,'').split('/')
26     };
27 }

 Google Chart 二维码链接

 1 function qrcode(data, size, level, margin) {
 2     size = size || 96;
 3     level = level || 'L';
 4     margin = margin | 0;
 5     return [
 6         'http://chart.apis.google.com/chart?cht=qr',
 7         '&chs=' + size + 'x' + size,
 8         '&chld=' + level + '|' + margin,
 9         '&chl=' + encodeURIComponent(data)
10     ].join('');
11 }

   使用:

//直接拼链接
 $("#qrcode").append("<img style='width:96px;height:96px;' src='http://chart.googleapis.com/chart?cht=qr&chld=L|0&chs=96x96&chl=" + encodeURIComponent(urlValue) + "'/>");
//通过脚本
 $("#qrcode").append("<img style='width:96px;height:96px;' src='" + qrcode(urlValue) + "'/>");

 扩展JS某个原型的方法

 1     String.prototype.endWith = function (endstr) {
 2         var reg = new RegExp(endstr + "$");
 3         return reg.test(this);
 4     }
 5     String.prototype.startWith = function (startstr) {
 6         var reg = new RegExp("^" + startstr);
 7         return reg.test(this);
 8     }
 9     if (isMobile.Any()) {
10         var link = '/login/indexmobile';
11         //alert(window.location.href);
12         //alert(window.location.href.toLowerCase());
13         //alert('indexmobile'.endWith("indexmobile"));
14         if (!window.location.href.toLowerCase().endWith('indexmobile')) {//加上该判断,防止自引入时,导致无限循环!
15             window.location = link;
16         }
17     }

 一般处理程序之验证码

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Drawing;
 4 using System.Linq;
 5 using System.Web;
 6 using System.Web.SessionState;
 7 using System.Web.UI.WebControls;
 8 
 9 namespace Wedo.BusInfo.WebUI.ashx
10 {
11     /// <summary>
12     /// 验证码
13     /// </summary>
14     public class testCode : IHttpHandler, IRequiresSessionState
15     {
16         public void ProcessRequest(HttpContext context)
17         {
18             string checkCode = CreateCode(6);
19             context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
20             context.Session["_Login_ValidateCode"] = checkCode;
21             CreateImage(checkCode, context);
22         }
23 
24         private string CreateCode(int codeLength)
25         {
26             string so = "1,2,3,4,5,6,7,8,9,0,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
27             string[] strArr = so.Split(',');
28             string code = "";
29             Random rand = new Random();
30             for (int i = 0; i < codeLength; i++)
31             {
32                 code += strArr[rand.Next(0, strArr.Length)];
33             }
34             return code;
35         }
36 
37         private void CreateImage(string code, HttpContext context)
38         {
39             Bitmap image = new Bitmap(15 * code.Length, 20);
40             Graphics g = Graphics.FromImage(image);
41             WebColorConverter ww = new WebColorConverter();
42             g.Clear((Color)ww.ConvertFromString("#EFEFEF"));
43             Random random = new Random();
44             //画图片的背景噪音线
45             for (int i = 0; i < 12; i++)
46             {
47                 int x1 = random.Next(image.Width);
48                 int x2 = random.Next(image.Width);
49                 int y1 = random.Next(image.Height);
50                 int y2 = random.Next(image.Height);
51                 g.DrawLine(new Pen(Color.LightGray), x1, y1, x2, y2);
52             }
53             Font font = new Font("Courier New", 16, FontStyle.Bold | FontStyle.Italic);//首选等宽字体,如:Courier New,Consolas等,确保宽度一定,否则不同的字符,长度不一致!
54             System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(
55                 new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.Gray, 1.2f, true);
56             g.DrawString(code, font, brush, 0, 0);
57             //画图片的前景噪音点
58             for (int i = 0; i < 10; i++)
59             {
60                 int x = random.Next(image.Width);
61                 int y = random.Next(image.Height);
62                 image.SetPixel(x, y, Color.White);
63             }
64 
65             //画图片的边框线
66             g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
67             System.IO.MemoryStream ms = new System.IO.MemoryStream();
68             image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
69             context.Response.ClearContent();
70             context.Response.ContentType = "image/Gif";
71             context.Response.BinaryWrite(ms.ToArray());
72             g.Dispose();
73             image.Dispose();
74         }
75 
76         public bool IsReusable
77         {
78             get
79             {
80                 return false;
81             }
82         }
83     }
84 }

效果图:

 等宽字体推荐

ConsolasCourierDroid Serif

DejaVu Sans MonoMonaco

 JavaScript的数组逻辑运算

1  <script>
2         function newline() {
3             document.write("<br/>");
4         }
5 </script>
 1<script>
 2       document.write([1] || [3, 4, 5] || [6, 7, 3]);
 3       newline();
 4       document.write([1] && [3, 4, 5] && [6, 7, 3]);
 5       newline();
 6       document.write(null || [3, 4, 5] || [6, 7, 3] && [23]);
 7       newline();
 8       document.write(null || [6, 7, 3] && [23] || [3, 4, 5]);
 9       newline();
10 </script>

结果:

1
6,7,3
3,4,5
23

结论:

先算&&再算||

||取第一个有效值

&&取最后一个有效值

结合boolean判断

 1    <script>
 2         //1、先算&&再算||
 3         //2、false&&any均为false
 4         //3、true||any 均为true
 5         //4、true&&有效对象 为有效对象
 6         //5、false||有效对象 为有效对象
 7         //结论:结果为决定因子,标注为红色
 8         document.write(false && false);//false
 9         document.write("<br/>");
10         document.write(false && true);//false
11         document.write("<br/>");
12         document.write(true || false);//true
13         document.write("<br/>");
14         document.write(true || true);//true
15         document.write("<br/>");
16         document.write(false && [1, 3]);//false
17         document.write("<br/>");
18         document.write(false && [1, 3] || [3, 4]);//[3,4]
19         document.write("<br/>");
20         document.write(true && [1, 3]);//&&左边有效,决定因子在右边。[1,3]
21         document.write("<br/>");
22         document.write([1, 3] && true);//&&左边有效,决定因子在右边。true!
23         document.write("<br/>");
24         document.write(false || [1, 3]);//[1,3]
25         document.write("<br/>");
26         document.write([1, 3] || false);//[1,3]
27         document.write("<br/>");
28         document.write(true || [1, 3] || [3, 4]);//true
29         document.write("<br/>");
30         document.write([3, 4] || false && [1, 3]);//[3,4]
31         document.write("<br/>");
32         document.write([3, 4] || true && [1, 3]);//[3,4]
33     </script>

这个在jQuery插件选项、脚本引入判断中常用,比如下面这段引入判断

1 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>
2 <script>window.jQuery || document.write('<script src="js/libs/jquery-1.7.1.min.js">/script>')</script>

 str.match(regex)与regex.exec(str)的Demo

  1 <!DOCTYPE html>
  2 <html xmlns="http://www.w3.org/1999/xhtml">
  3 <head>
  4     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  5     <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
  6     <link rel="icon" href="favicon.ico" type="image/x-icon" />
  7     <title>正则表达式regex.exec(str)与str.match(regex)</title>
  8     <style>
  9         body
 10         {
 11             font-family: 'Microsoft YaHei';
 12             font-size: 18px;
 13         }
 14 
 15         p
 16         {
 17             text-indent: 2em;
 18             font-size: 18px;
 19             font-weight: bold;
 20             border-left: solid #0026ff 8px;
 21             width: 800px;
 22             margin: 8px;
 23         }
 24 
 25         hr
 26         {
 27             margin: 10px auto;
 28         }
 29     </style>
 30 </head>
 31 <body>
 32     <h1>1、str.match(regex)</h1>
 33     <p>match属于字符串的方法</p>
 34     <p>
 35         (b+):所有匹配的b,比如bbb;(b)+:所有匹配的b的最后一个b,比如bbb的最后一个b
 36         (\d+):所有匹配的数字,比如345678;(\d)+:所有匹配的数字的最后一个,比如345678的最后一个8
 37     </p>
 38     <p>结论:根据返回结果可知如果<font color="red">"正则表达式"</font>有g全局,那么返回所有匹配结果[abbb345678,ab0,abbbbb6],
如果<font color="red">"正则表达式"</font>没有g全局,那么返回数组arr[0]为匹配的完整字串,后面是括号里的捕获[abbb345678,b,34];</p> 39 <script> 40 str = "abbb345678eftab0modabbbbb6"; 41 var reg = /a(b+)(\d+)/i;// 继续测试: var reg = /a(b+)(\d+)/ig 42 var arr = str.match(reg);//match属于字符串的方法 43 for (var i = 0; i < arr.length; i++) { 44 document.write(arr[i] + "<br/>"); 45 } 46 function newline() { 47 document.write("<br/>"); 48 } 49 </script> 50 <hr /> 51 52 53 <h1>2、regex.exec(str)</h1> 54 <p>exec属于正则的方法</p> 55 <p>结论:根据返回结果可知无论<font color="red">"正则表达式"</font>是否有g全局。
返回的数组arr[0]为匹配的完整字串,后面是括号里的捕获[abbb345678,b,34],即g有没有都无影响,<font color="blue">都是匹配第一组数据</font>,等价于不含有g全局标志的match。</p> 56 <script type="text/javascript"> 57 str = "abbb345678eftab0modabbbbb6"; 58 var reg = /a(b+)(\d+)/ig;// 继续测试: var reg = /a(b+)(\d+)/i 59 var arr = reg.exec(str);//exec属于正则的方法 60 for (var i = 0; i < arr.length; i++) { 61 document.write(i + ":" + arr[i] + "<br/>"); 62 } 63 </script> 64 <hr /> 65 66 67 <h1>3、g对regex.exec(str)的影响</h1> 68 <p> 69 结论:当一个具有g的<font color="red">"正则表达式"</font>调用exec()时,他将该对象的lastIndex设置到紧接这匹配子串的字符位置。
当第二次调用exec时将从lastIndex所指示的字符位置开始检索.利用这个特点可以<font color="blue">反复调用exec遍历所有匹配。</font>等价于具有g标志的str.match(regex). 70 </p> 71 <script type="text/javascript"> 72 73 str = "abbb345678eftab0modabbbbb6"; 74 document.write("regex.exec法<br/>") 75 var reg = /a(b+)(\d+)/ig;// then test: var reg = /a(b+)(\d+)/i(while死循环,浏览器会死的) 76 while ((arr = reg.exec(str)) != null) { 77 document.write("arr.length=" + arr.length + "<br/>"); 78 for (var i = 0; i < arr.length; i++) { 79 document.write(i + ":" + arr[i] + "<br/>"); 80 } 81 newline(); 82 } 83 document.write("<br/>如果只要arr[0],相当于str.match法<br/>") 84 var arrmatch = str.match(reg); 85 document.write("arrmatch.length=" + arrmatch.length + "<br/>"); 86 for (var i = 0; i < arrmatch.length; i++) { 87 document.write(i + ":" + arrmatch[i] + "<br/>"); 88 } 89 90 </script> 91 <hr /> 92 <h1>最终结论</h1> 93 str.match(regex)<br /> 94 <ol> 95 <li>regex有g:贪婪模式,返回所有匹配</li> 96 <li>regex没有g:返回第一个匹配,及第一匹配的<font color="red">group</font></li> 97 </ol> 98 regex.exec(str)<br /> 99 <ol> 100 <li>regex有g:返回第一个匹配,及第一匹配的<font color="red">group</font> 101 。重置lastIndex,可以不断重复调用,直到null时结束</li> 102 <li>regex没有g:返回第一个匹配,及第一匹配的<font color="red">group</font></li> 103 </ol> 104 </body> 105 </html>

最终结论

str.match(regex)

regex有g:贪婪模式,返回所有匹配

regex没有g:返回第一个匹配,及第一匹配的group

regex.exec(str)

regex有g:返回第一个匹配,及第一匹配的group 。重置lastIndex,可以不断重复调用,直到null时结束

regex没有g:返回第一个匹配,及第一匹配的group

regex没有g时候,str.match(regex)与regex.exec(str)等效

这里写的有点乱,参考这篇文章

JS原生XMLHttpRequest实现Ajax

 1 <script type="text/javascript">
 2         function createXHR() {
 3             var xhr = null;
 4             try {
 5                 // Firefox, Opera 8.0+, Safari,IE7+
 6                 xhr = new XMLHttpRequest();
 7             }
 8             catch (e) {
 9                 // Internet Explorer 
10                 try {
11                     xhr = new ActiveXObject("Msxml2.XMLHTTP");
12                 }
13                 catch (e) {
14                     try {
15                         xhr = new ActiveXObject("Microsoft.XMLHTTP");
16                     }
17                     catch (e) {
18                         xhr = null;
19                     }
20                 }
21             }
22             return xhr;
23         }
24         //在收到响应后相应数据会填充到XHR对象的属性,有四个相关属性会被填充:
25         //1. responseText:作为响应主体被返回的文本
26         //2. responseXML:如果响应内容的类型是”text/xml”或”application/xml”,这个属性将保存包含着相应数据的XML文档
27         //3. status:响应的HTTP状态(200,404,500等)
28         //4. statusText:HTTP状态说明
29         var xhr = createXHR();
30         //检查XHR对象的readyState属性,该属性表示请求/响应过程中的当前活动阶段,每当readyState值改变的时候都会触发一次onreadystatechange事件。必须在open前就指定该处理函数。
31         xhr.onreadystatechange = function () {
32             //readyState 
33             //0:请求未初始化;
34             //1:服务器已建立连接;
35             //2:请求已接受;
36             //3:请求处理中;
37             //4:请求已完成,且响应就绪。
38             if (xhr.readyState == 4 && xhr.status == 200) {
39                 console.log('Original Ajax: ' + xhr.responseText);
40             }
41         }
42         xhr.open('post', 'handler/info.ashx', true);//get或post,ashx需要发布后才可以访问
43         xhr.setRequestHeader("userdef", "haha");//open后,send前
44         xhr.send('{action:"getTime",id:"12"}');
45     </script>

 jQuery插件模板

 1 //记得把"pluginName" 改成你自己的插件名!
 2 //开始的分号是为了保证你脚本的完整性,避免和没加";"结束的对象、数组混合。
 3 ; (function ($) {
 4     //我们需要附加插件到jQuery的命名空间,否则插件在这个函数作用域之外便不可使用。
 5     //"el"应该是由jQuery选择器引擎返回的jQuery的对象或对象集合
 6     $.pluginName = function (el, options) {
 7         //插件默认配置,私有属性,仅可以从插件内部访问。
 8         var defaults = {
 9             propertyName: 'value',
10             //如果你的插件是事件驱动的,你需要为事件提供回调函数。在插件触发某一事件前或后调用这些函数,
11             //因此用户可以"绑定"自定义的函数到这些特定事件且不用修改代码。
12             onSomeEvent: function () { }
13         }
14 
15         //为了避免众多this产生混淆,使用"plugin"来引用当前的插件对象。
16         var plugin = this;
17 
18         //这是一个合并了默认属性(default)和用户提供的属性(options)之后的插件属性。
19         //它可以这么来访问:
20         //插件内部:plugin.settings.propertyName
21         //插件外部:myplugin.settings.propertyName(myplugin是一个插件实例)
22         plugin.settings = {}
23 
24         //插件对象被创建时候调用的构造函数
25         //这是一个私有函数,仅可以从插件内部调用
26         var init = function () {
27             //插件最终属性是合并default和options之后的属性
28             plugin.settings = $.extend({}, defaults, options);
29             //将目标元素作为插件的公有属性,这样就可通过插件来访问了
30             plugin.el = el;
31 
32             // 你的代码
33         }
34 
35         //共有属性,可以这么来调用
36         //插件内部:methodName(arg1, arg2, ... argn)
37         //插件外部:myplugin.publicMethod(arg1, arg2, ... argn)(myplugin是一个实例对象)
38         //public方法,仅作演示,可删!
39         plugin.foo_public_method = function () {
40             //你的代码
41         }
42 
43         //私有方法
44         //这些方法仅可以从插件内部调用
45         //methodName(arg1,arg2,...argn)
46         //私有方法,仅作演示,可删!
47         var foo_private_method = function () {
48             // 你的代码
49         }
50         //调用构造函数
51         init();
52     }
53 })(jQuery);

 去除注释

 1 ; (function ($) {
 2 
 3     $.pluginName = function (el, options) {
 4 
 5         var defaults = {
 6             propertyName: 'value',
 7             onSomeEvent: function () { }
 8         }
 9 
10         var plugin = this;
11 
12         plugin.settings = {}
13 
14         var init = function () {
15             plugin.settings = $.extend({}, defaults, options);
16             plugin.el = el;
17             // code goes here
18         }
19 
20         plugin.foo_public_method = function () {
21             // code goes here
22         }
23 
24         var foo_private_method = function () {
25             // code goes here
26         }
27 
28         init();
29 
30 } 31 32 })(jQuery);

 参考链接:jQuery模板

MAC键盘说明

Sublime Text 快捷键

 

JS实现HTML编码解码

 1 function htmlEncode(e) {
 2     var i, s = {
 3         "&amp;": /&/g, "&quot;": /"/g, "&#039;": /'/g,
 4         "&lt;": /</g, "&gt;": />/g, "<br/>": /\n/g,
 5         "&nbsp;": / /g, "&nbsp;&nbsp;": /\t/g
 6     }; 
 7     for (i in s) { 
 8         e = e.replace(s[i], i);
 9     }
10     return e;
11 };
12 
13 function htmlDecode(e) {
14     var i, s = {
15         "&": /&amp;/g, "\"": /&quot;/g, "'": /&#039;/g,
16         "<": /&lt;/g, ">": /&gt;/g, "\\n": /<br\/>/g,
17         " ": /&nbsp;/g, "\\t": /&nbsp;&nbsp;/g
18     };
19     for (i in s) {
20         e = e.replace(s[i], i);
21     }
22     return e;
23 };

 JS原型继承

 1    function Person(p_name, p_age) {
 2         this.name = p_name;
 3         this.age = p_age;
 4         this.say = function() {
 5             alert(this.name + this.age);
 6         }
 7     }
 8 
 9     function Student(p_no) {
10         this.no = p_no;
11         this.speak = function() {
12             alert(this.no + this.name + this.age);
13         }
14     }
15     Student.prototype = new Person("wjj", 28);
16     //1、Person实例继承了Person构造器里的方法和属性
17     //2、通过原型链传递继承的东西到Student
18     var stu = new Student(100);
19     stu.speak();
20     stu.say();
21     alert(Student.prototype.constructor);
22     //3、通过alert发现,构造器已经不是Student的了,而是Person的

 内存表现: 

 

 

posted @ 2014-04-24 18:40  凌晨风  阅读(250)  评论(0编辑  收藏  举报