admin管理员组

文章数量:1323023

I'm trying to update hash and then reload page.

$('a[name="' + fragment + '"]').remove(); //don't jump before window reloads
window.location.hash = fragment;
window.location.reload(true);

After reload window doesn't jump to anchor tag. How can I fix it?

I'm trying to update hash and then reload page.

$('a[name="' + fragment + '"]').remove(); //don't jump before window reloads
window.location.hash = fragment;
window.location.reload(true);

After reload window doesn't jump to anchor tag. How can I fix it?

Share Improve this question asked Dec 19, 2012 at 11:50 fedor.belovfedor.belov 23.4k28 gold badges96 silver badges135 bronze badges 3
  • Why would you use the hash, and then reload the page ? – adeneo Commented Dec 19, 2012 at 11:52
  • 1 I think you are better of by changing the href property: window.location.href = url + '#your-hash'; – Tim S. Commented Dec 19, 2012 at 11:52
  • The idea is to reload the page and then jump screen to specific place on the page – fedor.belov Commented Dec 19, 2012 at 12:07
Add a ment  | 

3 Answers 3

Reset to default 2

This is fairly trivial to achieve in jQuery if you are reloading the page. Just check the window.location.hash property when loading the page.

$(document).ready( function( ) {
    if( window.location.hash ) { // just in case there is no hash
        $(document.body).animate({
            'scrollTop':   $( window.location.hash ).offset().top
        }, 2000);
    }
});

The only caveat is that your hash matches the id of the element you are scrolling to.

Demo here

MOZILLA DEVELOPER NETWORK suggest using replace:

function reloadPageWithHash() {
  var initialPage = window.location.pathname;
  window.location.replace('http://example./#' + initialPage);
} 

@Tim S. my intention is absolutely not to steal your thunder but your very low key ment above is in my opinion the optimal solution to this question as it is simple, clean and tests successfully across a variety of browsers. I am therefore creating an answer of it on your behalf:

window.location.href = url#anchor

(where url can be the current page - or a different one as desired)

本文标签: javascriptGo to the anchor link after windowlocationreloadStack Overflow