开发者

Is it possible to trigger a javascript to run when a particular anchor is selected?

开发者 https://www.devze.com 2022-12-24 18:34 出处:网络
Say I have an anchor on a webpage like so: <a name=\"comegetit\"></a> Is there a way of running a javascript if the page is arrived at by a link that lands on this 开发者_如何学JAVAanch

Say I have an anchor on a webpage like so:

<a name="comegetit"></a>

Is there a way of running a javascript if the page is arrived at by a link that lands on this 开发者_如何学JAVAanchor? (e.g. a link like <a href="http://myawesomewebpage.com/page#comegetit"></a>). I don't think there is but I would like there to be.


If you only expect this one string as the URL anchor:

if(window.location.hash == '#comegetit'){
  // Do your stuff.
}

If you're doing anything else complex, you can also match window.location.hash against a regular expression.


I use Really Simple History (http://code.google.com/p/reallysimplehistory/)

Then, in my code I do something like this:

window.dhtmlHistory.create();
window.dhtmlHistory.initialize();   
window.dhtmlHistory.addListener(function(hash){
    // this is where you process your hash and do something special
    // and totally funky
});

This even gets fired on the initial page load, if you happen to bookmark a hash tag or whatnot.

Quite useful, and abstracts away all the browser specific B.S. that comes with window.location.hash

Josh


You can try to act on the onload event and check for the window.location content to extract the fragment identifier... it should work.

0

精彩评论

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

关注公众号