开发者

Javascript to respond to changes in the # portion of the url

开发者 https://www.devze.com 2023-01-20 20:57 出处:网络
I am trying to use jQuery to respond to changes in the url after the #. I\'ve done some searching, but I don\'t think I\'m using the right search terms.

I am trying to use jQuery to respond to changes in the url after the #. I've done some searching, but I don't think I'm using the right search terms.

To be clear, I want to be able to provide external links to a page like so:

<a href="example.com/foo/#home">home</a>

and to include internal links to change the content on the page dynamically:

&开发者_JAVA百科lt;a href="#site-index">site index</a>

Gmail does this. For example, I can link you straight to your sent box: https://mail.google.com/mail/u/0/#sent

Thanks.


Is this what you're looking for:

http://haineault.com/blog/37/

(function(){
  anchor = document.location.hash, handlers = [];

  jQuery.extend({
    anchorHandler: {
      add: function(regexp, callback) {
        if (typeof(regexp) == 'object') {
          jQuery.map(regexp, function(arg){
            args = {r: arg[0], cb: arg[1]};});}
        else  args = {r: regexp, cb: callback};
        handlers.push(args);
        return jQuery.anchorHandler;
      }
    }
  })(document).ready(function(){
    jQuery.map(handlers, function(handler){
      match = anchor.match(handler.r) && anchor.match(handler.r)[0] || false;
      if (match) handler.cb.apply(this, [match, (anchor || false)]);});});
})();

Add triggers like this:

$.anchorHandler
  .add(/\#ch\-cheatsheet/,    h.comment.showCheatsheet)
  .add(/\#comment\-compose/,  h.comment.showCompose)
  .add(/\#comment\-\d+/,      h.comment.focus);


Look into the HTML 5 hashchange event and the jQuery Back Button & Query plugin to provide that for older browsers.


I believe that the term you want is fragment.


I think the jQuery History plugin does exactly what you want to do.


Here is a super simple example:

if (location.hash != "")
{
    Location.hash.replace(
        new RegExp( "([^#?=&]+)(=([^&]*))?", "g" ),
            function( $0, $1, $2, $3 ){
                eval($1 + "='" + $3 + "'");
             });
}

This a method i've used in the past (in a kind of hacky way) to eval all the variable, this will turn the following:

#id=1&blah=cheese

into javascript variables of id and blah with the correct values, quick and simple :)


JQuery doesn't have an event to respond to hash changes in the URI. After the document is ready, you examine the hash and alter the page appropriately. You can intercept your hash anchors' click events and respond appropriately thereafter. Alternatively, you can create a synthetic "hash changed" event by inspecting window.location.hash on a timer.

0

精彩评论

暂无评论...
验证码 换一张
取 消