This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 10 years ago.
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(3)
还要注意页面上js的执行方式。例如,如果您执行以下操作:
这将返回 null,因为您将在加载文档之前调用该文档。
使用
window.onload
等待 dom 节点加载:Also be careful how you execute the js on the page. For example if you do something like this:
This will return null because you'd be calling the document before it was loaded.
Use
window.onload
to wait for the dom nodes to load:它可能是由以下原因引起的:
请发布您的代码。
It can be caused by:
Please, post your code.
document.getElementById
不起作用的原因可能有很多您的 ID 无效
<块引用>
ID 和 NAME 标记必须以字母 ([A-Za-z]) 开头,后面可以跟任意数量的字母、数字 ([0-9])、连字符 ("-")、下划线 (" _”)、冒号(“:”)和句点(“.”)。
(资源:什么是 id 属性的有效值HTML?)
你使用了一些已经在标题中用作
名称的 id(例如版权、作者...),它看起来很奇怪,但发生在我身上: 如果你是用IE看一下
(资源:http://www.phpied.com/getelementbyid-description-in-ie /)
您正在定位框架或 iframe 内的元素。在这种情况下,如果 iframe 加载父级同一域内的页面,您应该在查找元素之前定位
contentdocument
(资源:在框架内调用特定id )
当节点没有有效地加载到 DOM 中时,您只是在查找一个元素,或者可能是一个简单的拼写错误
我怀疑您使用相同的 ID 两次或更多次:在这种情况下
document.getElementById
应该至少返回第一个元素There could be many reason why
document.getElementById
doesn't workYou have an invalid ID
you used some id that you already used as
<meta>
name in your header (e.g. copyright, author... ) it looks weird but happened to me: if your 're using IE take a look at(resource: http://www.phpied.com/getelementbyid-description-in-ie/)
you're targeting an element inside a frame or iframe. In this case if the iframe loads a page within the same domain of the parent you should target the
contentdocument
before looking for the element(resource: Calling a specific id inside a frame)
you're simply looking to an element when the node is not effectively loaded in the DOM, or maybe it's a simple misspelling
I doubt you used same ID twice or more: in that case
document.getElementById
should return at least the first element