简体   繁体   English

我对document.getElementById的调用做错了什么

[英]What am I doing wrong with this call to document.getElementById

I have the following javascript code 我有以下javascript代码

var myDiv = document.getElementById("myDiv");
alert(myDiv);                
myDiv.style.display = 'none';

the call to alert(myDiv) succesfully shows that myDiv is not null and I see that the object (the div) has all the necessary properties set etc. alert(myDiv)的调用成功显示myDiv不为null,并且我看到对象(div)已设置了所有必需的属性,等等。

However, the call to myDiv.style.display = none results in an Object Required javascript error in IE 8. 但是,对myDiv.style.display = none的调用导致IE 8中的Object Required javascript错误。

Any pointers on what I need to check? 关于我需要检查的任何指示?

Thanks. 谢谢。

Make sure your html markup is valid. 确保您的html标记有效。 You can use validation service provided by w3c. 您可以使用w3c 提供的验证服务 Or if you are using any IDE check if it has validation facility 或者,如果您正在使用任何IDE,请检查它是否具有验证工具

Make sure this script is called at window.onload , not before. 确保在window.onload而不是之前调用此脚本。

Edit: also, make sure you avoid the common pitfall of doing this: 编辑:此外,请确保避免这样做的常见陷阱:

window.onload = foo() # PROBABLY WRONG

When really you wanted to do this: 当您真正想要这样做时:

window.onload = foo

Also, check that besides only attempting this after the DOM has loaded, that you don't have more than one element on the page with the same myDiv ID. 另外,请检查除了仅在DOM加载后才尝试执行此操作之外,还要检查页面上具有相同myDiv ID的元素是否不止一个。 View Source and try to find where this appears, make sure it isn't accidentally repeated. 查看源代码并尝试查找它的出现位置,确保不会意外重复出现。

Good luck! 祝好运!

An html element will/can have id and name. html元素将/可以具有ID和名称。 In my application we use master pages (asp.net) so when you place a control under a content page which is derived by master page, 在我的应用程序中,我们使用母版页(asp.net),因此当您将控件放在由母版页派生的内容页下时,

the id of the control will be like "ctl00_ctl00_ctlname" 控件的ID将类似于“ ctl00_ctl00_ctlname”

and

the name will have "ctl00$ctl00$ctlname" 名称将具有“ ctl00 $ ctl00 $ ctlname”

Now, if getElementById works fine in IE7(IE 7) and not in IE8(IE 8) then one possible reason is the value / attribute passed in getElementById method. 现在,如果getElementById在IE7(IE 7)中工作正常,而在IE8(IE 8)中则工作不正常,那么一个可能的原因是getElementById方法中传递的值/属性。 This is because IE7 used to find control by name if the id does not match. 这是因为IE7用于在ID不匹配的情况下按名称查找控件。

In short if you are passing the value of name attribute then the getElementById() will not work in IE8 简而言之,如果您传递name属性的值,则getElementById()在IE8中将不起作用

happy coding :) 快乐的编码:)

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

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