javascript document.anchors.length在firefox中返回1 [英] javascript document.anchors.length returning 1 in firefox

查看:65
本文介绍了javascript document.anchors.length在firefox中返回1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用javascript浏览页面中6个锚点的列表,以对它们进行一些操作.但是,循环未执行,因为anchors.length返回1.以下是我的代码段:

I am trying to run through a list of 6 anchors in a page using javascript to do some operations on them. However, the loop is not getting executed because anchors.length is return 1. The following is my code snippet:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript">
function load()
{
alert(document.anchors.length);
for (i = 0; i <= document.anchors.length; i++)
    {
        alert(document.anchors[i].innerHTML);
    }
}
</script>
</head>
<body onload="load()">
<div>        
<ul>
<a id="sectionlinks" href="page1.html">link 1</a></li>
<a id="sectionlinks" href="page2.html">link 2</a></li>
<a id="sectionlinks" href="page3.html">link 3</a></li>
<a id="sectionlinks" href="page4.html">link 4</a></li>
<a id="sectionlinks" href="page5.html">link 5</a></li>
<a id="sectionlinks" href="page6.html">link 6</a></li>
<ul>
</div>
</body>
</html>

这在IE9中工作正常.但是在Firefox和Chrome中,它的计数等于1.如果有人可以指出我在这里错过的内容,那将很棒.

This is working fine in IE9. But in Firefox and Chrome, it is saying that the count is equal to 1. Would be great if someone can point me to what I have missed here.

您可能已经猜到了,我是JS的新手,只是在学习它.

As you might have guessed, I am a newbie to JS and am just learning it.

推荐答案

至少,您正在学习正确的方法,继续前进!

At least, you're learning the correct way, keep going!

您做错了什么,是document.anchors是指锚链接(使用name属性的旧锚链接),而不是普通链接.例如,以下是锚点:

What you've done wrong is that document.anchors refers to anchor links (old anchor links using the name attribute), not normal links. For example, the following is an anchor:

<a name="tab"></a>

以下是链接:

<a href="/some/link"></a>

链接位于document.links HTMLCollection中,因此您可以使用document.links.length.

The links are in the document.links HTMLCollection, so you can use document.links.length.

如果要获取所有<a>元素,无论它们的属性是什么,都可以使用document.getElementsByTagName( 'a' ).length.

If you want to get all the <a> elements, no matter what's in their attribute, you can use document.getElementsByTagName( 'a' ).length.

这篇关于javascript document.anchors.length在firefox中返回1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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