Get hash value from url

前端 未结 5 1391
执念已碎
执念已碎 2020-12-24 07:06

I\'m trying to get the hash value after a link was clicked. Any ideas?

e.g.

The Link

index.html#needThis

This is my result:

5条回答
  •  梦谈多话
    2020-12-24 07:35

    update

    Modern browsers (not sure how back it goes) can extract the hash directly from anchor elements (so i added #5)


    Take your pick ..

    1. var hash = $(this).attr('href').split('#')[1];
    2. var hash = $(this).attr('href').replace(/^.*?#/,'');
    3. var href = $(this).attr('href'), hash = href.substr(href.indexOf('#')+1);
    4. var hash = $(this).attr('href').match(/#(.*$)/)[1];
    5. var hash = this.hash.substr(1);

    update

    Just revisited this and i believe that #2 can be improved to

    $(this).attr('href').replace(/^.*?(#|$)/,'');
    

    This way if no hash exists it will return empty instead of the whole url..

提交回复
热议问题