getElementById 在节点上不起作用
在这个简单的脚本中,我收到错误“obj.parentNode.getElementById 不是函数”,我不知道出了什么问题。
<script type="text/javascript">
function dosomething (obj) {
sibling=obj.parentNode.getElementById("2");
alert(sibling.getAttribute("attr"));
}
</script>
<body>
<div>
<a id="1" onclick="dosomething(this)">1</a>
<a id="2" attr="some attribute">2</a>
</div>
</body>
In this simple script i get the error "obj.parentNode.getElementById is not a function", and I have no idea, what is wrong.
<script type="text/javascript">
function dosomething (obj) {
sibling=obj.parentNode.getElementById("2");
alert(sibling.getAttribute("attr"));
}
</script>
<body>
<div>
<a id="1" onclick="dosomething(this)">1</a>
<a id="2" attr="some attribute">2</a>
</div>
</body>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
.getElementById()
位于文档中
,就像这样:由于 ID 应该是唯一的,因此不需要通过 ID 相对于任何其他元素(在本例中,在该父元素内部)查找元素的方法。此外,如果使用 HTML4,它们不应以数字开头,数字 ID 在 HTML5 中有效。
.getElementById()
is ondocument
, like this:Since IDs are supposed to be unique, there's no need for a method that finds an element by ID relative to any other element (in this case, inside that parent). Also, they shouldn't start with a number if using HTML4, a numberic ID is valid in HTML5.
将 .getElementById(id) 替换为 .querySelector('#'+id);
replace .getElementById(id) with .querySelector('#'+id);
如果节点是动态创建的并且尚未附加到主文档 dom 中,则
document.getElementById()
将不起作用。例如,对于 Ajax,并非所有节点都附加在任何给定点。在这种情况下,您要么需要显式跟踪每个节点的句柄(通常最适合性能),要么使用类似的方法来查找对象备份:
document.getElementById()
won't work if the node was created on the fly and not yet attached into the main document dom.For example with Ajax, not all nodes are attached at any given point. In this case, you'd either need to explicitly track a handle to each node (generally best for performance), or use something like this to look the objects back up: