简体   繁体   English

只有刷新页面后,getElementById才起作用

[英]getElementById works only after refreshing the page

I'm Trying to access results div in the results page of google.co.uk. 我正在尝试在google.co.uk的结果页面中访问结果div。 Using firebug one can see that the id of the div is "res" but for some reason getElementById('res') fails. 使用Firebug可以看到div的ID是“ res”,但是由于某种原因getElementById('res')失败。 to make things even weirder - if i refresh the page (F5 or ctrl+F5), the function succeeds. 使事情变得更奇怪-如果我刷新页面(F5或Ctrl + F5),函数将成功。

Also, if i look in the source code of the results page i dont see anything that looks like the DOM described in firebug. 另外,如果我查看结果页面的源代码,则看不到任何类似于firebug中描述的DOM的内容。

Why is this happening and how can i ensure getElementById('res') will succeed with any refresh by the user. 为什么会发生这种情况,以及如何确保用户getElementById('res')刷新getElementById('res')都会成功。

Thanks. 谢谢。

EDIT: im adding aa short code to simplify the problem. 编辑:我添加了一个简短的代码来简化问题。 after placing a query in google.co.uk the page redirects and the alert 'working' pops but the second alert doesnt. 在google.co.uk中进行查询后,页面将重定向,并且警报“正在工作”弹出,但第二个警报没有。 after refreshing, both alerts pop although the second one says 0 which is not right because the div has children according to the firebug DOM. 刷新后,两个警报都会弹出,尽管第二个警报会显示0,这是不正确的,因为div根据Firebug DOM有子级。

ps: i also failed to mention that im using greasmonkey ps:我也没有提到即时通讯使用greasmonkey

(function() {
alert('working');
var results = document.getElementById('res');
alert(results.childNodes.length);
})();
window.addEventListener("DOMContentLoaded", function () {
    var results = document.getElementById('res');
    alert(results.childNodes.length);
}, false);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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