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

标签 javascript anchor getelementbyid

我遇到了奇怪的失败。看来,如果我在 anchor 元素上同时具有 ID 和 NAME 属性,则 document.getElementById 会失败。如果我删除 NAME,它就会起作用。我在 Firefox 3.5(最新)中看到了这一点,但尚未检查其他浏览器。

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

最佳答案

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

我使用 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>

关于Javascript - 如果 anchor 也有名称属性,则 getElementById 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1289967/

相关文章:

javascript - 奇怪的行为 - getElementById()

javascript - 为什么我们不直接使用元素 ID 作为 JavaScript 中的标识符?

javascript - 将不同的图像强制设置为相同的高度,以便组合宽度填充固定的 div

自动完成选择后 JavaScript 清空输入

javascript - anchor URL 访问时突出显示 anchor ID

php - 如何强制 HTML 链接是绝对的?

javascript - 正则表达式 getElementById

javascript - 删除属性显示为 :none via Javascript 的页面上的 div

javascript - 将本 map 片导入XML以供跨平台应用程序使用

html - h3 和 anchor 标签样式问题