开发者

Javascript elements.length returning wrong count?

开发者 https://www.devze.com 2022-12-10 07:55 出处:网络
Ok, been scratching my head on this one for a bit now... seems related to this ol\' chestnut Here\'s my problem:

Ok, been scratching my head on this one for a bit now... seems related to this ol' chestnut

Here's my problem:

var testlength = theForm.elements.length;
var testlastelement = theForm.开发者_JS百科elements[testlength].type;

testlength returns 60

BUT!

testlastelement comes back as "undefined" (null or not an object)

What gives?

FWIW, my page has a bunch of inputs (i'm trying to loop through a form and grab names, values, etc)... the form inputs are contained within a table but the last elements (which are also types=image) are outside that table.


Use testlength - 1. Arrays are zero-based.


Arrays and HTMLCollections like form.elements in JavaScript have 0-based indexes, that means you have 60 elements, and their indexes are from 0 to 59, or from 0 to length-1


Well, the first element of an array has the index 0, therefore you should try this:

var testlastelement = theForm.elements[testlength-1].type;


You need testlength-1, since arrays are zeo-indexed. That is:

var testlastelement = theForm.elements[testlength-1].type;

Also, camelcase is the javascript standard. Probably better to write this as:

var testLastElement = theForm.elements[testLength-1].type;

At least be consistent. Your variable theForm is camelcased.

0

精彩评论

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