最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to execute a js function based on url hash url#nameoffunction - Stack Overflow

programmeradmin3浏览0评论

I saw some of websites executes a JavaScript function based on has in the URL. For example,

when I access

then the website executes a function based on #test

I can do it by checking location.href, but is there a better way?

I saw some of websites executes a JavaScript function based on has in the URL. For example,

when I access http://domain.com/jobs#test

then the website executes a function based on #test

I can do it by checking location.href, but is there a better way?

Share Improve this question asked May 20, 2011 at 19:11 MoonMoon 22.6k72 gold badges197 silver badges273 bronze badges 1
  • You asked right question friend (y) – Smile Commented Feb 27, 2014 at 6:29
Add a comment  | 

5 Answers 5

Reset to default 10

This is what i do:

window.onload = function(){
    var hash = (window.location.hash).replace('#', '');
    if (hash.length == 0) {
        //no hash do something
    }
    else {
        //else do something with hash
    }
}

demo: http://jsfiddle.net/maniator/XCjpy/show/#test
demo2: http://jsfiddle.net/maniator/XCjpy/show/
demo3: http://jsfiddle.net/maniator/XCjpy/show/#testing_again

If you don't need to support old browsers like IE6 and IE7 you can use:

window.onhashchange = function(){
  switch(location.hash) {
    case '#hash1':
      //do something
    break;
    case '#has2':
      //do something else
    break;
  }
}

But if you have to support older browsers you need to poll:

var oldHash = location.hash;
setInterval(function(){
  if(location.hash !== oldHash){
    oldHash = location.hash;
    //hash changed do something
  }
}, 120);

Live Demo

$(window).bind('hashchange', function() {
    var hash = document.location.hash;
    var func = hash.replace('#', '');
    eval(func + '()');
});

function asdf() {
    alert('asdf function');
}

function qwerty() {
    alert('qwerty function');
}

Note: eval() is dangerous. You should make a predefined array of safe functions, and call those.

Have a look at This.
See the property table.
location.hash should help you.

You could use a library like YUI to do this more elegantly, Take a look at the YUI Browser History Manager

http://developer.yahoo.com/yui/history/

发布评论

评论列表(0)

  1. 暂无评论