简体   繁体   中英

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

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:

<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);

查看HTML 5 hashchange事件和jQuery Back Button&Query插件 ,以为较旧的浏览器提供该事件。

我相信您想要的术语是碎片。

我认为jQuery History插件确实可以完成您想做的事情。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM