利用a标签自动解析URL

很多时候我们有从一个URL中提取域名,查询关键字,变量参数值等的需要,而万万没想到可以让浏览器方便地帮我们完成这一任务而不用我们写正则去抓取。方法就在JS代码里先创建一个a标签然后将需要解析的URL赋值给a的href属性,然后就得到了一切我们想要的了。

 var a = document.createElement('a');
a.href = 'http://www.cnblogs.com/wayou/p/';
console.log(a.host);

利用这一原理,稍微扩展一下,就得到了一个更加健壮的解析URL各部分的通用方法了。下面代码来自James的博客

 // This function creates a new anchor element and uses location
// properties (inherent) to get the desired URL data. Some String
// operations are used (to normalize results across browsers). function parseURL(url) {
var a = document.createElement('a');
a.href = url;
return {
source: url,
protocol: a.protocol.replace(':',''),
host: a.hostname,
port: a.port,
query: a.search,
params: (function(){
var ret = {},
seg = a.search.replace(/^\?/,'').split('&'),
len = seg.length, i = 0, s;
for (;i<len;i++) {
if (!seg[i]) { continue; }
s = seg[i].split('=');
ret[s[0]] = s[1];
}
return ret;
})(),
file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],
hash: a.hash.replace('#',''),
path: a.pathname.replace(/^([^\/])/,'/$1'),
relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],
segments: a.pathname.replace(/^\//,'').split('/')
};
}

生成随机字符串

利用Math.random和toString生成随机字符串,来自前一阵子看到的一篇博文

 function generateRandomAlphaNum(len) {
var rdmString = "";
for (; rdmString.length < len; rdmString += Math.random().toString(36).substr(2));
return rdmString.substr(0, len);
}

Math.floor的高效替代方案

利用好位操作符可以让我们获得效率上的提升,同时显得高端大气上档次。

|0和~~是很好的一个例子,使用这两者可以完美替代Math.floor。在处理像素及动画位移等效果的时候会很有用,因为我们需要整数,而此方法比Math.floor或parseInt效率都要高。性能比较见此

var foo = (12.4 / 4.13) | 0;//结果为3
var bar = ~~(12.4 / 4.13);//结果为3

注:整理有个重要的知识点:当 ~ 运算符充当非整型数据类型的操作数时,该值在运算执行之前被强制为 int 类型,该运算符的返回值为 int 类型。

顺便说句,!!将一个值方便快速转化为布尔值 !!window===true 。

禁止别人以iframe加载你的页面

下面的代码已经不言自明并,没什么好多说的。

 if (window.location != window.parent.location)
  window.parent.location = window.location;

最新文章

  1. Microservice Anti-patterns
  2. final关键字(final是最终的)
  3. Jersey 2 + Maven + Tomcat + IntelliJ IDEA 搭建RESTful服务
  4. hdu 4381(背包变形)
  5. cocos2dx游戏资源加密之XXTEA
  6. Nginx + Apache 反向代理
  7. linux命令学习-1-less
  8. css3 翻牌效果
  9. Spring框架中 配置c3p0连接池 完成对数据库的访问
  10. Open-Falcon 监控系统监控 MySQL/Redis/MongoDB 状态监控
  11. 【JavaScript数组】
  12. flying中的AOP和IOC
  13. vue v-for循环的用法
  14. 【c# 数据库】 多表链接
  15. 网络流24题 gay题报告
  16. 李宏毅机器学习笔记4:Brief Introduction of Deep Learning、Backpropagation(后向传播算法)
  17. XStream进行xml和bean互转
  18. Spark_RDD之RDD操作简介
  19. [蓝桥] 基础练习 数列排序(java)
  20. django项目创建启动 ORM操作

热门文章

  1. merge into Oracle里的 saveOrUapdate
  2. Mac下配置node.js 和react-native
  3. MySQL 删除数据表
  4. window连接linux nfs服务器 —— 网络错误 53
  5. POJ 2230 (欧拉路)
  6. Vim简明教程【CoolShell】(转)
  7. 《JavaScript dom 编程艺术》 placeholder占位符IE8兼容办法。
  8. 用webclient.DownloadFile下载exe文件时大小为0
  9. localStorage 的基本使用
  10. php中json_decode()和json_encode()