getElementById在节点上不起作用 [英] getElementById doesn't work on a node

查看:403
本文介绍了getElementById在节点上不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个简单的脚本中,我得到错误obj.parentNode.getElementById不是一个功能,我不知道,是什么问题。

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>


推荐答案

.getElementById() 位于文档,如下所示:

document.getElementById("2");

由于ID 应该是唯一的,所以不需要一个方法它通过ID相对于任何其他元素(在这种情况下,在该父项内)中找到一个元素。另外,如果使用HTML4,那么他们不应该使用数字,在HTML5中有一个数字ID 有效。

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在节点上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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