1. 浏览器变编辑器
  1. data:text/html, <style type="text/css">#e{position:absolute;top:;right:;bottom:;left:;}</style><div id="e"></div><script src="http://d1n0x3qji82z53.cloudfront.net/src-min-noconflict/ace.js" type="text/javascript" charset="utf-8"></script><script>var e=ace.edit("e");e.setTheme("ace/theme/monokai");e.getSession().setMode("ace/mode/javascript");</script>

深度拷贝

  1. function deepCopy(p, c) {
  2.     var c = c || {};
  3.     for (var i in p) {
  4.       if (typeof p[i] === 'object') {
  5.         c[i] = (p[i].constructor === Array) ? [] : {};
  6.         deepCopy(p[i], c[i]);
  7.       } else {
  8.          c[i] = p[i];
  9.       }
  10.     }
  11.     return c;
  12.   }
  1.  
  2. 生成随机字符串
  1. // 生成随机字符串
  2. var strRandom = "qwertyuioplkjhgfdsazxcvbnm0123456789";
  3. function getRamdomStr(){
  4. var str = "", len = strRandom.length,
  5. index = Math.floor(len*Math.random());
  6. str = strRandom.substring(index-1,index);
  7. return str;
  8. }
  9. function generateClassName(){
  10. var arr = [];
  11. for(var i = 0; i< 12; i++){
  12. arr.push(getRamdomStr());
  13. }
  14. return arr.join("");
  15. }
  1.  
  2. curry化函数
  1. // 【通用curry化函数】
  2. function curry(fn) {
  3. var slice = Array.prototype.slice,
  4. stored_args = slice.call(arguments, 1);
  5. return function () {
  6. var new_args = slice.call(arguments),
  7. args = stored_args.concat(new_args);
  8. return fn.apply(null, args);
  9. }
  10. }
  11.  
  12. // 测试
  13. function add(x, y) {
  14. return x + y;
  15. }
  16. // 将一个函数curry化获得一个新的函数
  17. var newadd = curry(add, 5);
  18. console.log(newadd(4));
  19.  
  20. // 另一种选择--直接调用新函数
  21. console.log(curry(add, 6)(7));

计数器

  1. var setup = function () {
  2. var count = 0;
  3. return function () {
  4. return (count += 1);
  5. };
  6. };
  7.  
  8. // 用法
  9. var next = setup();
  10. next();

获取地址参数

  1. var getValueParam = function(key){
  2. var url = window.location.href,
  3. para = url.split('?')[1],
  4. arrparam = [],
  5. val = undefined;
  6. if(para.length){
  7. arrparam = para.split('&');
  8. for( var i = 0; i<arrparam.length; i++ ){
  9. if(arrparam[i].split("=")[0] == key){
  10. val = arrparam[i].split("=")[1];
  11. break;
  12. }
  13. }
  14. }
  15. return val;
  16. };

php数组赋值js变量

  1. var data = <?php echo json_encode($data) ?>

弹出居中

  1. function getValue ($target){
  2. var h = $(document).scrollTop()+($(window).height()-$target.height())/2;
  3. var w = ($(window).width()-$target.width())/2
  4. return {
  5. t : h,
  6. l : w
  7. }
  8. }

form表单Ajax提交

  1. $('form').submit(function(e){
  2. e.preventDefault();
  3. var postData = $(this).serializeArray();
  4. var formURL = $(this).attr("action");
  5. $.ajax({
  6. url : formURL,
  7. type: "POST",
  8. data : postData,
  9. dataType : "json",
  10. success:function(data, textStatus, jqXHR)
  11. {
  12. if(textStatus == 'success'){
  13. console.log(data, textStatus, jqXHR);
  14. }
  15. //data: return data from server
  16. },
  17. error: function(jqXHR, textStatus, errorThrown)
  18. {
  19. //if fails
  20. }
  21. });
  22. });

腾讯视频嵌入代码

  1. <iframe class="video_iframe" style=" z-index:1; " src="http://v.qq.com/iframe/player.html?vid=m0144ws2h0q&amp;width=300&amp;height=200&amp;auto=0" allowfullscreen="" frameborder="0" height="200" width="300"></iframe>

网页代码编辑器

  1. data:text/html, <style type="text/css">.e{position:absolute;top:0;right:0;bottom:0;left:0;}</style><div class="e" id="editor"></div><script src="http://d1n0x3qji82z53.cloudfront.net/src-min-noconflict/ace.js" type="text/javascript" charset="utf-8"></script><script>var e=ace.edit("editor");e.setTheme("ace/theme/monokai");e.getSession().setMode("ace/mode/javascript");</script>
  1. scp
  2. 上端口大写P 为参数,2222 表示更改SSH端口后的端口,如果没有更改SSH端口可以不用添加该参数
  3. 获取文件:
  4. scp -P 2222 root@www.legcloud.com:/root/test.tar.gz /home/test.tar.gz
  5. 上传目录:
  6. scp -P 2222 -r /home/dirname/ root@www.legcloud.com:/root/dirname/

判断是否为数组的函数: isArray()

  1. // 支付宝同学在用的
  2. if (value instanceof Array ||
  3. (!(value instanceof Object) &&
  4. (Object.prototype.toString.call((value)) == '[object Array]') ||
  5. typeof value.length == 'number' &&
  6. typeof value.splice != 'undefined' &&
  7. typeof value.propertyIsEnumerable != 'undefined' &&
  8. !value.propertyIsEnumerable('splice'))) {
  9. return 'array';
  10. }
  11.  
  12. // 最直接的、简单的方式(在不同 iframe 中创建的 Array 并不共享 prototype)
  13. var arr = [];
  14. arr instanceof Array; // true
  15. arr.constructor == Array; //true
  16.  
  17. // 基于iframe的情况 使用 Douglas Crockford 的方法是可以解决这个问题(《JavaScript 语言精粹》P61)
  18. var is_array = function(value) {
  19. return value &&
  20. typeof value === 'object' &&
  21. typeof value.length === 'number' &&
  22. typeof value.splice === 'function' &&
  23. !(value.propertyIsEnumerable('length'));
  24. };
  25.  
  26. // 更简单的方法,也是jQuery 正在使用的。淘宝的 kissy 也是使用这种方式
  27. var isArray = function(obj) {
  28. return Object.prototype.toString.call(obj) === '[object Array]';
  29. }
  30.  
  31. // 大而全而cool 判断类型
  32. var is = function (obj,type) {
  33. return (type === "Null" && obj === null) ||
  34. (type === "Undefined" && obj === void 0 ) ||
  35. (type === "Number" && isFinite(obj)) ||
  36. Object.prototype.toString.call(obj).slice(8,-1) === type;
  37. }

1、&&和if

  1. // &&和
  2. var a = ;
  3. a == && ( b = ,console.log(b)) ; // 0
  4.  
  5. // 上面代码等同于
  6. var a = ;
  7. if( a == ){
  8. b = ,console.log(b);
  9. }
  10. a == && ( b = ,console.log(b)) // 0
  11.  
  12. // 以下还会返回值
  13. var a = ;
  14. a != && ( b = ,console.log(b)) ; // false

2、判断IE

  1. 常规的判断已经阻挡不了NBIE了,没有msie。。用它:
    // IE11
  2. !!navigator.userAgent.match(/Trident\/\./)
  3. // 或者
  4. Object.hasOwnProperty.call(window, "ActiveXObject") && !window.ActiveXObject
  5.  
  6. // IE6
    var ie6 = !-[1,]&&!window.XMLHttpRequest;
  7.  
  8. // IE7
    var ie7 = (navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion.match(/7./i)=="7.")

3、移动端常用

  1. // 移动端判断屏幕高度
  2. document.documentElement.clientHeight
  3. // browser info and capability
  4. var _ua = window.navigator.userAgent;
  5. // isRetina
  6. window.devicePixelRatio && window.devicePixelRatio > 1
  7. // isIDevice
  8. (/iphone|ipod|ipad/i).test(_ua)
  9. // isMobileChrome
  10. _ua.indexOf('Android') > -1 && (/Chrome\/[.0-9]*/).test(_ua)
  11. // isMobileIE
  12. _ua.indexOf('Windows Phone') > -1
  13. // isMobileSafari
  14. isIDevice && _ua.indexOf('Safari') > -1 && _ua.indexOf('CriOS') < 0;
  15. // isTablet
  16. (isMobileSafari && _ua.indexOf('iPad') > -1) || (isMobileChrome && _ua.indexOf('Mobile') < 0);

Platform = {

list :[{"name":"iOS",

"value" : 1

},{"name":"Android",

"value" :2

},{"name":"weixin",

"value" :3

}],

getName : function(){

var name = this.getInfo().name;

return name;

},

getValue : function(){

var val = this.getInfo().value;

return val;

},

getInfo : function(){

var list = this.list,

regObj = this.judgeReg,

obj = {"name":"weixin","value":2};

for(var i=0;i<list.length; i++){

if(regObj[list[i]['name']]){

obj = list[i];

break;

}

}

return obj;

},

judgeReg : {

"iOS" : !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/),

"Android" : navigator.userAgent.indexOf('Android') > -1 || navigator.userAgent.indexOf('Linux') > -1,

"weixin" :  /MicroMessenger/.test(navigator.userAgent)

}

};

  1. 横竖屏函数判断
  2. function orientationChange() {
  3. switch (window.orientation) {
  4. case 0: // Portrait
  5. case 180: // Upside-down Portrait
  6. // Javascript to setup Portrait view
  7. alert('Portrait');
  8. break;
  9. case -90: // Landscape: turned 90 degrees counter-clockwise
  10. case 90: // Landscape: turned 90 degrees clockwise
  11. // Javascript to steup Landscape view
  12. alert('Landscape');
  13. break;
  14. }
  15. }
  16. window.addEventListener(("onorientationchange" in window || "orientation" in window) ? "orientationchange" : "resize", orientationChange, false);

4、deffer

  1. var Promise = function () {
  2. this.thens = [];
  3. };
  4. Promise.prototype = {
  5. resolve: function () {
  6. var t = this.thens.shift(), n;
  7. t && (n = t.apply(null, arguments), n instanceof Promise && (n.thens = this.thens));
  8. },
  9. then: function (n) {
  10. return this.thens.push(n), this;
  11. }
  12. }
  13. function f1() {
  14. var promise = new Promise();
  15. setTimeout(function () {
  16.  
  17. alert(1);
  18. promise.resolve();
  19. }, 5500)
  20.  
  21. return promise;
  22. }
  23.  
  24. function f2() {
  25. var promise = new Promise();
  26. setTimeout(function () {
  27.  
  28. alert(2);
  29. promise.resolve();
  30. }, 1500)
  31.  
  32. return promise;
  33. }
  34.  
  35. function f3() {
  36. var promise = new Promise();
  37. setTimeout(function () {
  38.  
  39. alert(3);
  40. promise.resolve();
  41. }, 1500)
  42.  
  43. return promise;
  44.  
  45. }
  46.  
  47. function f4() {
  48. alert(4);
  49. }
  50.  
  51. f1().then(f2).then(f3).then(f4);

5、更多常用方法

  1. String.prototype.isMobile = function(){
  2. var pattern = /^0{0,1}(13[0-9]|14[6|7]|15[0-3]|15[5-9]|18[0-9]|17[0-9])[0-9]{8}$/;
  3. return pattern.test( this );
  4. }
  5. String.prototype.isEmail = function(){
  6. var pattern = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
  7. return pattern.test( this );
  8. }
  9. String.prototype.isUrl = function(){
  10. var pattern = /([\w-]+\.)+[\w-]+.([^a-z])(\[\w-\.\?%&=]*)?|[a-zA-Z0-9\-\.][\w-]+.([^a-z])(\[\w-\.\?%&=]*)?/;
  11. return pattern.test( this );
  12. }
  13. String.prototype.isChinese = function(){
  14. var pattern = /^[\u4e00-\u9fa5]+$/;
  15. return pattern.test( this );
  16. }
  17. String.prototype.isEnglish = function(){
  18. var pattern = /^[a-zA-Z]+$/;
  19. return pattern.test( this );
  20. }
  21. var BASE = {
  22. // html模板替换,用于html和数据相分离
  23. // 模板中的变量用‘{}’包起来,‘{}’内的字符作为变量替换掉需要的内容
  24. // 模板写法: var dom = '<li class="item {selected}" val="{value}">{text}</li>'
  25. // 【方法调用】:BASE.regReplace(dom,{selected:1,value:2,text:3});
  26. // 输出结果:"<li class="item 1" val="2">3</li>"
  27. regReplace : function(str,data,reg){
  28. if (!reg){
  29. reg = /\{\w*\}/g;
  30. }
  31. return str.replace(reg,function(match,pos){
  32. var s = '';
  33. var command = match.substring(1,match.length-1);
  34. if (data[command]){
  35. s = data[command];
  36. }
  37. return s;
  38. });
  39. },
  40. // 在数组中查找元素,如果存在,返回所在下标,如果不存在,则返回-1
  41. // 【方法调用】:BASE.isInArr(1,[2,3,1]);
  42. isInArr : function(item, arr){
  43. if( arr.length > 0 ){
  44. for( var i = 0; i < arr.length; i++ ){
  45. if( arr[i] == item ){
  46. return i;
  47. break;
  48. }
  49. }
  50. return -1;
  51. }else{
  52. return -1;
  53. }
  54. },
  55. // 在数组中删除指定元素,如果存在,返回删除后的数组,如果不存在,返回undefined
  56. // 【方法调用】:BASE.removeInArr(1,[2,3,1]);
  57. removeInArr : function(item, arr){
  58. var index = this.isInArr(item, arr);
  59. if (index > -1) {
  60. arr.splice(index, 1);
  61. return arr;
  62. }else{
  63. return undefined;
  64. }
  65. },
  66. // 得到最大天数
  67. getMaxDays : function(year, month){
  68. var dt = new Date(year, month - 1, '01');
  69. dt.setDate(1);
  70. dt.setMonth(dt.getMonth() + 1);
  71. cdt = new Date(dt.getTime()-1000*60*60*24);
  72. return cdt.getDate();
  73. },
  74. getCookie : function (a) {
  75. var b;
  76. b = a + "=";
  77. offset = document.cookie.indexOf(b);
  78. if (offset != -1) {
  79. offset += b.length;
  80. end = document.cookie.indexOf(";", offset);
  81. if (end == -1) {
  82. end = document.cookie.length;
  83. }
  84. return document.cookie.substring(offset, end);
  85. }
  86. else {
  87. return "";
  88. }
  89. }
  90. };

6、图片尺寸

  1. // 传统做法
  2. var imgLoad = function (url, callback) {
  3. var img = new Image();
  4.  
  5. img.src = url;
  6. if (img.complete) {
  7. callback(img.width, img.height);
  8. } else {
  9. img.onload = function () {
  10. callback(img.width, img.height);
  11. img.onload = null;
  12. };
  13. };
  14.  
  15. };
  16. // 1、保证回调执行顺序:error > ready > load;2、回调函数this指向img本身
  17. // 2、增加图片完全加载后的回调、提高性能
  18.  
  19. /**
  20. * 图片头数据加载就绪事件 - 更快获取图片尺寸
  21. * @param {String} 图片路径
  22. * @param {Function} 尺寸就绪
  23. * @param {Function} 加载完毕 (可选)
  24. * @param {Function} 加载错误 (可选)
  25. * @example imgReady('http://x.autoimg.cn/www/common/images/logo.png', function () {
  26. alert('size ready: width=' + this.width + '; height=' + this.height);
  27. });
  28. */
  29. var imgReady = (function () {
  30. var list = [], intervalId = null,
  31.  
  32. // 用来执行队列
  33. tick = function () {
  34. var i = 0;
  35. for (; i < list.length; i++) {
  36. list[i].end ? list.splice(i--, 1) : list[i]();
  37. };
  38. !list.length && stop();
  39. },
  40.  
  41. // 停止所有定时器队列
  42. stop = function () {
  43. clearInterval(intervalId);
  44. intervalId = null;
  45. };
  46.  
  47. return function (url, ready, load, error) {
  48. var onready, width, height, newWidth, newHeight,
  49. img = new Image();
  50.  
  51. img.src = url;
  52.  
  53. // 如果图片被缓存,则直接返回缓存数据
  54. if (img.complete) {
  55. ready.call(img);
  56. load && load.call(img);
  57. return;
  58. };
  59.  
  60. width = img.width;
  61. height = img.height;
  62.  
  63. // 加载错误后的事件
  64. img.onerror = function () {
  65. error && error.call(img);
  66. onready.end = true;
  67. img = img.onload = img.onerror = null;
  68. };
  69.  
  70. // 图片尺寸就绪
  71. onready = function () {
  72. newWidth = img.width;
  73. newHeight = img.height;
  74. if (newWidth !== width || newHeight !== height ||
  75. // 如果图片已经在其他地方加载可使用面积检测
  76. newWidth * newHeight > 1024
  77. ) {
  78. ready.call(img);
  79. onready.end = true;
  80. };
  81. };
  82. onready();
  83.  
  84. // 完全加载完毕的事件
  85. img.onload = function () {
  86. // onload在定时器时间差范围内可能比onready快
  87. // 这里进行检查并保证onready优先执行
  88. !onready.end && onready();
  89.  
  90. load && load.call(img);
  91.  
  92. // IE gif动画会循环执行onload,置空onload即可
  93. img = img.onload = img.onerror = null;
  94. };
  95.  
  96. // 加入队列中定期执行
  97. if (!onready.end) {
  98. list.push(onready);
  99. // 无论何时只允许出现一个定时器,减少浏览器性能损耗
  100. if (intervalId === null) intervalId = setInterval(tick, 40);
  101. };
  102. };
  103. })();
  104. 调用例子:
  105.  
  106. imgReady('http://www.google.com.hk/intl/zh-CN/images/logo_cn.png', function () {
  107. alert('size ready: width=' + this.width + '; height=' + this.height);
  108. });

7、iframe跨域

  1. function Messenger(win) {
  2. // save the pointer to the window which is interacting with
  3. this.win = win;
  4. this.init();
  5. }
  6.  
  7. // postMessage API is supported
  8. Messenger.prototype.init = function () {
  9. var self = this;
  10. var receiver = function (event) {
  11. // Some IE-component browsers fails if you compare
  12. // window objects with '===' or '!=='.
  13. if (event.source != self.win) return;
  14. (self.onmessage || function () {}).call(self, event.data);
  15. };
  16. if (window.addEventListener)
  17. window.addEventListener('message', receiver, false);
  18. else if (window.attachEvent)
  19. window.attachEvent('onmessage', receiver);
  20. };
  21.  
  22. Messenger.prototype.send = function (data) {
  23. this.win.postMessage(data, '*');
  24. };
  25.  
  26. Messenger.initInParent = function (frame) {
  27. return new this(frame.contentWindow);
  28. };
  29.  
  30. Messenger.initInIframe = function () {
  31. return new this(window.parent);
  32. };
  33.  
  34. // in IE, postMessage API is not supported
  35. if (!window.postMessage && window.attachEvent) {
  36. // redefine the init method
  37. Messenger.prototype.init = function () {
  38. var isSameOrigin = false;
  39. // test if the two document is same origin
  40. try {
  41. isSameOrigin = !!this.win.location.href;
  42. } catch (ex) {}
  43. if (isSameOrigin) {
  44. this.send = this.sendForSameOrigin;
  45. this.initForSameOrigin();
  46. return;
  47. }
  48.  
  49. // different origin case
  50. // init the message queue, which can guarantee the messages won't be lost
  51. this.queue = [];
  52. if (window.parent == this.win) {
  53. this.initForParent();
  54. } else {
  55. this.initForFrame();
  56. }
  57. };
  58.  
  59. Messenger.prototype.initForSameOrigin = function () {
  60. var self = this;
  61. document.attachEvent('ondataavailable', function (event) {
  62. if (!event.eventType ||
  63. event.eventType !== 'message' ||
  64. event.eventSource != self.win)
  65. return;
  66. (self.onmessage || function () {}).call(self, event.eventData);
  67. });
  68. };
  69.  
  70. Messenger.prototype.sendForSameOrigin = function (data) {
  71. var self = this;
  72. setTimeout(function () {
  73. var event = self.win.document.createEventObject();
  74. event.eventType = 'message';
  75. event.eventSource = window;
  76. event.eventData = data;
  77. self.win.document.fireEvent('ondataavailable', event);
  78. });
  79. };
  80.  
  81. // create two iframe in iframe page
  82. Messenger.prototype.initForParent = function () {
  83. var fragment = document.createDocumentFragment();
  84. var style = 'width: 1px; height: 1px; position: absolute; left: -999px; top: -999px;';
  85. var senderFrame = document.createElement('iframe');
  86. senderFrame.style.cssText = style;
  87. fragment.appendChild(senderFrame);
  88. var receiverFrame = document.createElement('iframe');
  89. receiverFrame.style.cssText = style;
  90. fragment.appendChild(receiverFrame);
  91.  
  92. document.body.insertBefore(fragment, document.body.firstChild);
  93. this.senderWin = senderFrame.contentWindow;
  94. this.receiverWin = receiverFrame.contentWindow;
  95.  
  96. this.startReceive();
  97. };
  98.  
  99. // parent page wait the messenger iframe is ready
  100. Messenger.prototype.initForFrame = function () {
  101. this.senderWin = null;
  102. this.receiverWin = null;
  103.  
  104. var self = this;
  105. this.timerId = setInterval(function () {
  106. self.waitForFrame();
  107. }, 50);
  108. };
  109.  
  110. // parent page polling the messenger iframe
  111. // when all is ready, start trying to receive message
  112. Messenger.prototype.waitForFrame = function () {
  113. var senderWin;
  114. var receiverWin;
  115. try {
  116. senderWin = this.win[1];
  117. receiverWin = this.win[0];
  118. } catch (ex) {}
  119. if (!senderWin || !receiverWin) return;
  120. clearInterval(this.timerId);
  121.  
  122. this.senderWin = senderWin;
  123. this.receiverWin = receiverWin;
  124. if (this.queue.length)
  125. this.flush();
  126. this.startReceive();
  127. };
  128.  
  129. // polling the messenger iframe's window.name
  130. Messenger.prototype.startReceive = function () {
  131. var self = this;
  132. this.timerId = setInterval(function () {
  133. self.tryReceive();
  134. }, 50);
  135. };
  136.  
  137. Messenger.prototype.tryReceive = function () {
  138. try {
  139. // If we can access name, we have already got the data.
  140. this.receiverWin.name;
  141. return;
  142. } catch (ex) {}
  143.  
  144. // if the name property can not be accessed, try to change the messenger iframe's location to 'about blank'
  145. this.receiverWin.location.replace('about:blank');
  146. // We have to delay receiving to avoid access-denied error.
  147. var self = this;
  148. setTimeout(function () {
  149. self.receive();
  150. }, 0);
  151. };
  152.  
  153. // recieve and parse the data, call the listener function
  154. Messenger.prototype.receive = function () {
  155. var rawData = null;
  156. try {
  157. rawData = this.receiverWin.name;
  158. } catch (ex) {}
  159. if (!rawData) return;
  160. this.receiverWin.name = '';
  161.  
  162. var self = this;
  163. var dataList = rawData.substring(1).split('|');
  164. for (var i = 0; i < dataList.length; i++) (function () {
  165. var data = decodeURIComponent(dataList[i]);
  166. setTimeout(function () {
  167. (self.onmessage || function () {}).call(self, data);
  168. }, 0);
  169. })();
  170. };
  171.  
  172. // send data via push the data into the message queue
  173. Messenger.prototype.send = function (data) {
  174. this.queue.push(data);
  175. if (!this.senderWin) return;
  176. this.flush();
  177. };
  178.  
  179. Messenger.prototype.flush = function () {
  180. var dataList = [];
  181. for (var i = 0; i < this.queue.length; i++)
  182. dataList[i] = encodeURIComponent(this.queue[i]);
  183. var encodedData = '|' + dataList.join('|');
  184. try {
  185. this.senderWin.name += encodedData;
  186. this.queue.length = 0;
  187. } catch (ex) {
  188. this.senderWin.location.replace('about:blank');
  189. var self = this;
  190. setTimeout(function () {
  191. self.flush();
  192. }, 0);
  193. }
  194. };
  195.  
  196. }
  197.  
  198. // 父页面
  199. var messenger = Messenger.initInParent(document.getElementById('iframe'));
  200. messenger.onmessage = function (data) {
  201. var newline = '\n';
  202. var text = document.createTextNode(data + newline);
  203. document.getElementById('output').appendChild(text);
  204. };
  205.  
  206. function sendMessage() {
  207. var message = document.getElementById('message');
  208. messenger.send(message.value);
  209. message.value = '';
  210. }
  211.  
  212. // 子页面
  213. var messenger = Messenger.initInIframe();
  214. messenger.onmessage = function (data) {
  215. var newline = '\n';
  216. var text = document.createTextNode(data + newline);
  217. document.getElementById('output').appendChild(text);
  218. };
  219.  
  220. function sendMessage() {
  221. var message = document.getElementById('message');
  222. messenger.send(message.value);
  223. message.value = '';
  224. }

8、发布订阅模型

  1. var PubSub = {handlers: {}}
  2. PubSub.on = function(eventType, handler) {
  3. if (!(eventType in this.handlers)) {
  4. this.handlers[eventType] = [];
  5. }
  6.  
  7. this.handlers[eventType].push(handler);
  8. return this;
  9. }
  10. PubSub.emit = function(eventType) {
  11. var handlerArgs = Array.prototype.slice.call(arguments, 1);
  12. for (var i = 0; i < this.handlers[eventType].length; i++) {
  13. this.handlers[eventType][i].apply(this, handlerArgs);
  14. }
  15. return this;
  16. }

9、关于this作用域

  1. // 兼容性更好的 bind
  2. if (!Function.prototype.bind) {
  3. Function.prototype.bind = function() {
  4. var __method = this;
  5. var args = Array.prototype.slice.call(arguments);
  6. var object = args.shift();
  7. return function() {
  8. return __method.apply(object,
  9. args.concat(Array.prototype.slice.call(arguments)));
  10. }
  11. }
  12. }
  1. // 最简单的 bind (ie9以上,不可取)
  2. Function.prototype.bind = function (scope) {
  3. var fn = this;
  4. return function () {
  5. return fn.apply(scope);
  6. };
  7. }
  8. // 例子
  9. var foo = {
  10. x: 3
  11. }
  12. var bar = function(){
  13. console.log(this.x);
  14. }
  15. bar(); // undefined
  16. var boundFunc = bar.bind(foo);
  17. boundFunc(); //
  18. // 适用场景:事件绑定回调和setTimeout回调
  19. // 1 事件绑定
  20. var logger = {
  21. x: 0,
  22. updateCount: function(){
  23. this.x++;
  24. console.log(this.x);
  25. }
  26. }
  27. // 原始函数
  28. document.querySelector('button').addEventListener('click', function(){
  29. logger.updateCount();
  30. });
  31. // 改造后
  32. document.querySelector('button').addEventListener('click', logger.updateCount.bind(logger));
  33.  
  34. // 2 setTimeout
  35. // 原始函数
  36. render: function () {
  37. this.$el.html(this.template());
  38. setTimeout(this.afterRender, 0);
  39. }
  40. // 改造后
  41. render: function () {
  42. this.$el.html(this.template());
  43. setTimeout(this.afterRender.bind(this), 0);
  44. }
  45. // Tidier Event Binding With querySelectorAll
  46. Array.prototype.forEach.call(document.querySelectorAll('.klasses'), function(el){
  47. el.addEventListener('click', someFunction);
  48. });
  49.  
  50. // 改造后
  51. var unboundForEach = Array.prototype.forEach,
  52. forEach = Function.prototype.call.bind(unboundForEach);
  53.  
  54. forEach(document.querySelectorAll('.klasses'), function (el) {
  55. el.addEventListener('click', someFunction);
  56. });

10、jquery多版本

  1. <script type="text/javascript" src="/jquery.1.7.js"></script>
  2. var jQuery_1_7 = jQuery.noConflict(true);
  3. jQuery_1_7('.class').on(callback);

11、常用正则

  1. 匹配 UTF- 中文:^[\x{4e00}-\x{9fa5}]+$
  2. 匹配包含全角字符的 UTF- 中文:^[\x{4e00}-\x{9fa5}A-Za-z0-9_]+$
  3. 匹配 GB2312/GBK 中文:^[".chr(0xa1)."-".chr(0xff)."]+$
  4. 匹配包含全角字符的 GB2312/GBK 中文:^[".chr(0xa1)."-".chr(0xff)."A-Za-z0-9_]+$
  5. 匹配 HTML 标记:< (\S*?)[^>]*>.*?|< .*? />
  6. 匹配邮件地址:\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
  7. 匹配网址 URL:[a-zA-z]+://[^\s]*
  8. 匹配加区号的国内电话号码:\d{}-\d{}|\d{}-\d{}
  9. 匹配 QQ 号:[-][-]{,}
  10. 匹配邮政编码:[-]\d{}(?!\d)
  11. 匹配身份证号码:\d{}|\d{}
  12. 匹配 ip 地址:\d+\.\d+\.\d+\.\d+

12、地址转义

  1. var encodeRFC5987ValueChars = function (str) {
  2. return encodeURIComponent(str).
  3. // Note that although RFC3986 reserves "!", RFC5987 does not,
  4. // so we do not need to escape it
  5. replace(/['()]/g, escape). // i.e., %27 %28 %29
  6. replace(/\*/g, '%2A').
  7. // The following are not required for percent-encoding per RFC5987,
  8. // so we can allow for a little better readability over the wire: |`^
  9. replace(/%(?:7C|60|5E)/g, unescape);
  10. };
    //添加反斜杠

function escapeRegExp(str) {
  return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
}

  1.  

13 安装压缩

  1. npm install uglify-js -g

javascript常用方法和技巧的更多相关文章

  1. Javascript常用方法函数收集(二)

    Javascript常用方法函数收集(二) 31.判断是否Touch屏幕 function isTouchScreen(){ return (('ontouchstart' in window) || ...

  2. 12个实用的 Javascript 奇淫技巧

    这里分享12个实用的 Javascript 奇淫技巧.JavaScript自1995年诞生以来已过去了16个年头,如今全世界无数的网页在依靠她完成各种关键任务,JavaScript曾在Tiobe发布的 ...

  3. 初学者学习JavaScript的实用技巧!

    Javascript是一种高级编程语言,通过解释执行.它是一门动态类型,面向对象(基于原型)的直译语言.它已经由欧洲电脑制造商协会通过ECMAScript实现语言标准化,它被世界上的绝大多数网站所使用 ...

  4. 你想的到想不到的 javascript 应用小技巧方法

    javascript 在前端应用体验小技巧继续积累. 事件源对象 event.srcElement.tagName event.srcElement.type 捕获释放 event.srcElemen ...

  5. JavaScript一些基础技巧和注意事项,你了解这些吗?

    总结了一些JavaScript在开发编码中的使用技巧,如有不对,欢迎指正. 一.JavaScript在HTML和XHTML的使用 使用<script>元素有两种方式:直接在页面中嵌入Jav ...

  6. Javascript 编程小技巧总结(部分内容借鉴他人)

    1 – 使用===,而不是== ==(或!=)操作符在需要的时候会自动执行类型转换.===(或!==)操作不会执行任何转换.它将比较值和类型,而且在速度上也被认为优于==. 2 – 使用闭包实现私有变 ...

  7. JavaScript学习总结-技巧、有用函数、简洁方法、编程细节

    整理JavaScript方面的一些技巧.比較有用的函数,常见功能实现方法,仅作參考 变量转换 //edit http://www.lai18.com var myVar = "3.14159 ...

  8. jQuery 选择器和JavaScript 选择器的技巧与异常原因

    jquery的选择器借鉴了css选择器,核心依然依靠JavaScript的getElementById()和getElementsByTagName()方法,但是他封装了2个方法,让jquery选择器 ...

  9. JavaScript 性能优化技巧分享

    JavaScript 作为当前最为常见的直译式脚本语言,已经广泛应用于 Web 应用开发中.为了提高Web应用的性能,从 JavaScript 的性能优化方向入手,会是一个很好的选择. 本文从加载.上 ...

随机推荐

  1. python自动化之model进阶操作一

    联合索引 遵循最左前缀索引 verbose_name 会在表名后面加s verbose_name_plural 就是表的原始名称 元信息 class UserInfo(models.Model): n ...

  2. oracle查询指定月份数据

    SELECT * FROM [表名]       where  to_number(to_char([表中日期字段],'mm')) = [要查找的月份]

  3. Mysql 多实例实施步骤

    基本理论:利用同一套安装程序,不同配置文件,不同启动程序,不同数据目录.有公用资源,也有私有资源. 实现步骤: 1.正常安装mysql,二进制安装或者编译安装. 2.创建mysql多实例总目录,总目录 ...

  4. windows服务初识

    参考网址1:http://www.vchome.net/dotnet/dotnetdocs/dotnet38.htm 参考网址2:http://zhidao.baidu.com/link?url=7- ...

  5. 清除浮动元素的margin-top失效原因(更改之前的错误)

    //样式代码body,div{ margin:; padding:; } .box1{ background:#900; width:200px; height:200px; margin:20px ...

  6. CPP/类/成员函数访问权限

  7. 关于在MySql的decimal中犯的一个错-此篇文章目的在于警醒自己

    今天在运行一段程序的时候报了Out of range value错误,网上的解释是说这个值与数据库字段类型不匹配,然而程序里面设置的是BigDecimal,数据库设置的是decimal,没有多想就把s ...

  8. python模拟随机游走

    在python中,可以利用数组操作来模拟随机游走. 下面是一个单一的200步随机游走的例子,从0开始,步长为1和-1,且以相等的概率出现.纯Python方式实现,使用了内建的 random 模块: # ...

  9. cogs1538 [AHOI2005]LANE 航线规划

    套路题+裸题 首先肯定离线,倒过来处理,删边->加边 连边的时候,如果不连通就连,否则在这两个点的链上打个覆盖标记,查询的时候输出没被覆盖的路径条数 #include<cstdio> ...

  10. linux提权 searchsploit 使用规范

    使用 searchsploit 时,要把整个控制台最大化,这样才能显示完整的漏洞信息. 查看漏洞帮助文件: