简体   繁体   中英

How can I link to an anchor tag that doesn't exist until the Javascript has created it?

I have a page that has a set of <div> elements, and each one has an anchor tag associated with it. It looks something like this:

<a name="anchor-0"></a>
<div id="div0">Some stuff</div>
<a name="anchor-1"></a>
<div id="div1">More stuff</div>
<a name="anchor-2"></a>
<div id="div2">Yet more stuff</div>

The problem is that this set of <div> and <a> tags are generated by Javascript, and so they don't exist until after the page has been created. When I create a link like this:

http://www.mywebsite.com/mypage.html#anchor-2

... it loads the page but does not jump to the anchor-2 position, which is only created some time after the browser has had time to execute the Javascript that generated it.

How can I get the browser to move to the selected anchor tag position once the Javascript has generated them?


Here is essentially what the Javascript that is generating the HTML looks like:

function init() {
  gapi.client.setApiKey('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
  gapi.client.load('blogger', 'v2', function() {
    var request = gapi.client.blogger.posts.list({
      'blogId': 'xxxxxxxxxxxxxxxxxxxxxxxx',
      'fields': 'items(content,title)'
    });
    request.execute(function(response) {
    var main = document.getElementById("main");
    var anchor = 0;
      for (var i = 0; i < response.items.length; i++)
      {
        var Div = document.createElement("div")
        $(Div).append(response.items[i].title);
        $(main).append(Div);
        anchor = document.createElement("a");
        anchor.name = "anchor-" + anchor;
        anchor = anchor +1;

      }
    });
  });
}

after creation of element, you could do:

location.hash = "#anchor-2";

or using scrollIntoView

element = document.getElementById('your_element-id');
element.scrollIntoView();

get the hash value from url, by doing something like::

var hashVal = window.location.hash.substr(1);
//then jump to that hash
location.hash = "#" + hashVal;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM