开发者

Should I access a form by name, id or by array index? [duplicate]

This question already has answers here: Closed 10 years ago.

Possible Duplicate:

Best Practice: Access form elements by HTML id or name attribute?

The forms on my site all have "id" attributes as follows...f0,f1,f2..., and this is how I access them. My understanding is that Javascript creates an aray that hold the forms and I can access them this开发者_C百科 was as well.

By id:

var a='f0';
var c=document.forms[a].elements;

By array index:

var c=document.forms[0].elements;

By name:

var a='f0';
var c=document.forms[a].elements;

Which way is better, I just picked by id as a starting point.


ID and Name are 2 different things:

var a='f0';
var c=document.forms[0].elements[a];

is accessing the element by name

example

<input name="f0" value="value" />

accessing by id is doene this way

var a='f0';
var c=document.getElementById(a);


If I have more than one on the page I use the id, there is less room for confusion and its more expressive and intuitive for any developers that are in the code after you.


Stick with what you've got - ID is more explicit. Index is nearly arbitrary and will cause headaches if the code is ever changed.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜