开发者

Following an anchor to content on another page that isn't created until after the DOM is ready

To boil it down, I have two pa开发者_StackOverflow社区ges. Simplified, they could be represented this way.

Page 1

<html>
    <a href="page-2.html#section-A">Link to section A</a>
</html>

Page 2

<html>
    <script>        
        // Assume jQuery
        $(document).ready(function(){
            $('#wrapper').append($('<a name="section-A">Here is Section A</a><p>Some more content here.</p>'));
        });
    </script>
    <div id="wrapper"></div>
</html>

The problem with this is that when you click on the link in Page 1 that url, say "http://www.mydomain.com/page-2.html#section-A" is followed, yet the content that the anchor links to is not generated until after the DOM loads, which is too late considering that the URL is loaded first.

If the problem isn't clear let me know and I will attempt to clarify further, but if anyone has any initial thoughts on how to get a scenario like this working please let me know.


In the second page, the code in your "ready" handler can check the page location. If the location has something like '#wrapper' in it, then your javascript can reset the location.

$(document).ready(function(){
  $('#wrapper').append($('<a name="section-A">Here is Section A</a><p>Some more content here.</p>'));
  if (document.location.hash === '#wrapper')
    document.location.hash = '#wrapper';
});

I'll try this out to see if it actually works. :-)

edit OK here's a test page: http://gutfullofbeer.net/hash1.html

There are two links: one has the hash in it ('#hello' in my case) and one doesn't. When you click the second one, you'll notice that you see the "hello" section at the bottom of the page. When you click the first one, you go to the same page but the "hello" section won't be visible (unless your browser window is really gigantic).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜