document.onload和getElementById()不合作 [英] document.onload and getElementById() don't cooperate

查看:199
本文介绍了document.onload和getElementById()不合作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

小组,


我偶然发现了一些奇怪的东西。


我将问题简化为:

带有一些JS的简单页面:


< span id =" testid">



< / span>


< script type =" text / javascript">

function alertID(){

var someID = document.getElementById(" testid");

alert(someID);

}


//加载后调用它

document.onload = alertID();

< / script>


将产生一个警告说[对象]

如预期的那样。

但是如果我在跨度之前编程''函数,就像这样,它会产生

null。


< script type =" text / javascript">

function alertID(){

var someID = document.getElementById(" testid");

alert(someID);

}

//在船尾叫它加载

document.onload = alertID();

< / script>


< span id =" testid">



< / span>

这对我来说是个惊喜,因为我在思考(并希望)

函数将在页面加载后进行评估。

似乎JS正在尝试该函数,然后找不到div(因为它

还不在页面上),并且给我null,而不是在加载页面后评估

函数。


我在IE6上有这种行为和Firefox。


有人可以对此有所了解吗?


问候,

Erwin Moller

推荐答案

Erwin Moller escreveu:
Erwin Moller escreveu:
这让我感到意外,因为我在思考(并希望)
函数将在页面加载后进行评估。
似乎JS正在尝试该函数,然后找不到d iv(因为它还没有在页面上),并且给了我null,而不是在加载页面后评估
函数。
That came as a surprise to me because I was thinking (and hoping) the
function would be evaluated AFTER the page loads.
It seems that JS is trying the function, then NOT finds the div (because it
is not on the page yet), and gives me null back, instead of evaluating the
function AFTER loading the page.




" document.onload = alertID();"应该是document.onload = alertID;

-

Jonas Raoni Soares Silva
http://www.jsfromhell.com



"document.onload = alertID();" should be "document.onload = alertID;"
--
Jonas Raoni Soares Silva
http://www.jsfromhell.com


Jonas Raoni escreveu:
Jonas Raoni escreveu:
Erwin Moller escreveu:
Erwin Moller escreveu:
这让我感到意外,因为我在思考(并希望)
函数将在页面加载后进行评估。看来JS正在尝试这个函数,然后找不到div(因为它还没有在页面上),并且给了我null,而不是在加载之后评估
函数page。
That came as a surprise to me because I was thinking (and hoping) the
function would be evaluated AFTER the page loads.
It seems that JS is trying the function, then NOT finds the div (because it
is not on the page yet), and gives me null back, instead of evaluating the
function AFTER loading the page.



" document.onload = alertID();"应该是document.onload = alertID;



"document.onload = alertID();" should be "document.onload = alertID;"




啊,更改文档到窗口 :b

-

Jonas Raoni Soares Silva
http://www.jsfromhell.com



Ah, change the "document" to "window" :b
--
Jonas Raoni Soares Silva
http://www.jsfromhell.com




Erwin Moller写道:

Erwin Moller wrote:
//加载后调用它
document.onload = alertID();
// call it after loading
document.onload = alertID();




你想要

document.onload = alertID;

或更高

window.onload = alertID;


你的作业只是打电话alertID(它有调用alertID())和

然后将返回值赋给文件

对象的onload属性。你需要做的是将onload属性设置为你想要在事件被触发时调用的函数




-


Martin Honnen
http://JavaScript.FAQTs。 com /


这篇关于document.onload和getElementById()不合作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆