javascript - jQuery: lightweight way to write and read parameters to URL hash? - Stack Overflow

I'm using jQuery and I'd like a lightweight plugin to write and read hash parameters from a U

I'm using jQuery and I'd like a lightweight plugin to write and read hash parameters from a URL.

For example, I'd like to be able to read a URL like index.html#color=red&day=monday and get { color: 'red', day: 'monday' }.

I'd also like to be able to write parameters to the hash, checking for the presence of a variable, and adding or updating it as appropriate.

Does anyone know a lightweight plugin that can do this, or do I need to write my own?

Obviously BBQ does all of this and much more, but I don't need all the history management, and I'm loath to include a lot of code I don't need.

I'm using jQuery and I'd like a lightweight plugin to write and read hash parameters from a URL.

For example, I'd like to be able to read a URL like index.html#color=red&day=monday and get { color: 'red', day: 'monday' }.

I'd also like to be able to write parameters to the hash, checking for the presence of a variable, and adding or updating it as appropriate.

Does anyone know a lightweight plugin that can do this, or do I need to write my own?

Obviously BBQ does all of this and much more, but I don't need all the history management, and I'm loath to include a lot of code I don't need.

Share Improve this question asked Jan 31, 2012 at 12:01 RichardRichard 33k30 gold badges111 silver badges146 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

this will work, you can put it in a function or use it straight forwardly:

  var hash = top.location.hash.replace('#', '');
    var params = hash.split('&');
    var result = {};
    for(var i = 0; i < params.length; i++){
       var propval = params[i].split('=');
       result[propval[0]] = propval[1];
    }

purl can read fragment params:

$.url("index.html#color=red&day=monday").fparam("color"); // returns "red"

To write them you can use jquery's $.param() helper. Here's a fiddle

Not sure of a plugin that is lightweight, but you could use something like

    var hashdata = new Object();

    jQuery.each(window.location.hash.replace(/^#/,'').split('&'), function(i,t){

       var s = t.split('=');
       hashdata[s[0]] = s[1];

   });

Which if i'm correct should return an object of the hash data in the url. Then knowing the current hash data, you could use window.location.hash to change that as and when you want

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745389654a4625603.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信