如果anchor也有name属性,则Javascript - getElementById失败

时间:2009-08-17 19:38:05

标签: javascript anchor getelementbyid

我遇到了一个奇怪的失败。似乎如果我在锚元素上同时具有ID和NAME属性,则document.getElementById将失败。如果我删除了NAME,它就可以了。我在Firefox 3.5(最新版)中看到了这一点,但尚未检查其他浏览器。

这是一个错误还是故意的?

1 个答案:

答案 0 :(得分:4)

我从来没有听说过这样的错误,所以我试图重现它并失败了。这表明你误解了这个问题,或者至少没有提供足够的信息。

我使用Firefox 3.5和以下代码进行了测试。

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">
<title>Test of getElementById with named anchors</title>
<h1>Test of getElementById with named anchors</h1>

<h2><a name="one" id="one">First section</a></h2>
<p>The quick brown fox</p>

<h2><a name="two" id="second">Second section</a></h2>
<p>The quick brown fox</p>

<script type="text/javascript">    
if (document.getElementById('one')) {
        document.write("<p>First section found - id matches name<\/p>");
}

if (document.getElementById('second')) {
        document.write("<p>Second section found - id does not match name<\/p>");
}
</script>
相关问题