Showing posts with label firefox. Show all posts
Showing posts with label firefox. Show all posts

Sunday, April 29, 2007

使用 js 获取网页 url 参数

使用 js 获取网页 url 参数,在 firefox 中很好用:

// get_url.js
String.prototype.getQuery = function(name)
{
var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
var r = this.substr(this.indexOf("\?")+1).match(reg);
if (r!=null) return unescape(r[2]); return null;
}

var url = location.search;

写一张页面,静态动态无所谓,加载文件 get_url.js,然后试着调用它:

window.alert("a"); // 获取 url 参数 a 的值
window.alert("b"); // 获取 url 参数 b 的值

Firefox 中书签可以使用命令行式方式,比如我有两个博客页,一个名为 m,一个名为 n。那么可以添加一个书签,参数照下面方式设置:
  • 名称:MDZ 的博客
  • 地址:file:///website/blog.html?blog=%s
  • 定制关键字:blog
然后写一个名为 blog.html 的页面放在 file:///website/ 目录下,具体看个人的设置。在页面的 script 标签中写入:

switch(url.getQuery("blog")) {
case "m":
window.location = "http://m.blogspot.com/";
break;
case "n":
window.location = "http://n.blogspot.com/";
break;
default:
document.write("Sorry, wrong parameter!");
}

以后就可以使用 firefox 的书签关键字加参数浏览我的博客啦:

blog m
blog n

声明:String.prototype.getQuery 函数来自于网络,谢谢这位网友!