开发者

Strange problem with document.getElementsByTagName("a")

Why doesn't it recognise 'number' as a variable in the following code, second line?

var number = document.getElementsByTagName("a").length;
var link = document.getElementsByTagName("a")[number].href;

Of course it works with any real number instead of the开发者_如何转开发 variable.


the array returned by document.getElementsByTagName("a") is 0-based, so, by definition, the index you're seeking doesn't exist. I suppose you probably mean this:

var number = document.getElementsByTagName("a").length;
var link = document.getElementsByTagName("a")[number-1].href;

:)

edit:

try using firebug to dump the values to the console for debugging - the problem will quickly become obvious :)

var number = document.getElementsByTagName("a").length;
console.log("number = "+number);
var link = document.getElementsByTagName("a")[number-1].href;


JavaScript arrays are zero-based, so, you will need to use number-1 to get the last element.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜