[英]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. 我的页面有一组<div>
元素,每个页面都有一个与之关联的锚标记。 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. 问题在于这组<div>
和<a>
标记是由Javascript生成的,因此直到创建页面后它们才存在。 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. ...它会加载页面,但不会跳转到anchor-2
位置,该位置仅在浏览器有时间执行生成该页面的Javascript后的一段时间才会创建。
How can I get the browser to move to the selected anchor tag position once the Javascript has generated them? Javascript生成浏览器后,如何使浏览器移动到选定的定位器标签位置?
Here is essentially what the Javascript that is generating the HTML looks like: 本质上,这是生成HTML的Javascript的样子:
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 或使用scrollIntoView
element = document.getElementById('your_element-id');
element.scrollIntoView();
get the hash value from url, by doing something like:: 通过执行以下操作从url获取哈希值:
var hashVal = window.location.hash.substr(1);
//then jump to that hash
location.hash = "#" + hashVal;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.