JavaScript и имена arr[somevar]

asm

Пофигист
bkonst
во первых getElementById работает намного медленнее!!!
во вторых upd[cat] скорее всего именно name а не ID
 

bkonst

.. хочется странного?...
kruglov
Естественно. Вернее, или буду писать шаблон сразу с нормальными ID, или воспользуюсь генератором форм, который не только автоматом проставит уникальные ID, но и повесит клиентскую проверку на Javascript в зависимости от типа поля.

Точно так же можно спросить, что вы будете делать, если у вас будет две одинакого названных формы.

vasa_c
HTML 4.01:
id = name [CS]
This attribute assigns a name to an element. This name must be unique in a document.
...
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
'[' и ']' не допускаются.

И вообще мы от темы отклонились.

-~{}~ 15.06.06 15:58:

во первых getElementById работает намного медленнее!!!
Здрась.... мы его 1000 раз в цикле вызывать собрались?

во вторых upd[cat] скорее всего именно name а не ID
Я про свой пример говорил.
 

asm

Пофигист
Автор оригинала: bkonst
Здрась.... мы его 1000 раз в цикле вызывать собрались?
А откуда ты знаешь? может собирается... Да и вообще это не довод в пользу твоего вaрианта.
+ лишний ID.

-~{}~ 15.06.06 15:07:

Автор оригинала: kruglov
asm
document.forms[formName]
предпочитаю не давать имена формам редко на странице бывает больше одной
 

bkonst

.. хочется странного?...
asm
Дык, клинические случаи не рассматриваются. В случае острой страсти к циклам getElementById вызывается 1 раз снаружи.

.... кстати, откуда такая информация о медленности getElementById? Ты ведь сам не проверял, не так ли?
 

asm

Пофигист
bkonst
на форме 1000 элементов :)))

проверь сам не веришь мне :)
 

bkonst

.. хочется странного?...
asm
На форме 1000 элементов?! Так-так-так. Что дальше придумаешь? ;)

проверь сам не веришь мне
Так я ж и проверил! Смотри:

Код:
<form name="sample" id="sample">
<input name="test" id="test" type="text">
</form>

<script type="text/javascript">
var time1 = new Date().getTime();
var element;
for (var i=0; i<100000; i++) {
  element = document.getElementById('test');
};
alert(new Date().getTime() - time1);

var time1 = new Date().getTime();
var element;
for (var i=0; i<100000; i++) {
  element = document.forms['sample'].elements['test'];
};
alert(new Date().getTime() - time1);
</script>
В Firefox получаем значения 1515 и 4453, в IE 6 - 2078 и 3750

Мне кажется, что это определенно довод в сторону моего варианта, не так ли?
(Экономим на спичках, однако)
 

AdminGorkyRu

Новичок
Автор оригинала: bkonst
Можно привести кусочек этого стандарта? Что-то я не припомню в DOM такой возможности.
Насколько мне известно JavaScript это не только DOM... или нет???

Для приведения кусочков этого стандарта предлагаю обратиться к Netscape JavaScript Reference (http://docs.sun.com/source/816-6408-10/)... там все написано...
 

bkonst

.. хочется странного?...
Автор оригинала: AdminGorkyRu
Насколько мне известно JavaScript это не только DOM... или нет???
Разумеется, это еще и ECMAScript.

Для приведения кусочков этого стандарта предлагаю обратиться к Netscape JavaScript Reference (http://docs.sun.com/source/816-6408-10/)... там все написано...
Спасибо. Посмотрел http://docs.sun.com/source/816-6408-10/document.htm, но, к сожалению, этого (document[formName]) синтаксиса не нашел. Нашел:
You can refer to the anchors, forms, and links of a document by using the anchors, forms, and links arrays
но это далеко от того, что было предложено изначально. Можно сделать скидку на мое плохое зрение и всё-таки процитировать нужное место стандарта?
 

AdminGorkyRu

Новичок
Код:
Form object
Object. Lets users input text and make choices from Form elements such as checkboxes, radio buttons, and selection lists. You can also use a form to post data to a server.

HTML syntax
To define a form, use standard HTML syntax with the addition of JavaScript event handlers:

<FORM
   NAME="formName"
   TARGET="windowName"
   ACTION="serverURL"
   METHOD=GET | POST
   ENCTYPE="encodingType"
   [onReset="handlerText"]
   [onSubmit="handlerText"]>
</FORM>

HTML attributes
NAME="formName" specifies the name of the Form object. You can access this value using the name property, and you can use this name when indexing the forms array.

TARGET="windowName" specifies the window that form responses go to. When you submit a form with a TARGET attribute, server responses are displayed in the specified window instead of the window that contains the form. windowName can be an existing window; it can be a frame name specified in a <FRAMESET> tag; or it can be one of the literal frame names _top, _parent, _self, or _blank; it cannot be a JavaScript expression (for example, it cannot be parent.frameName or windowName.frameName). You can access this value using the target property.

ACTION="serverURL" specifies the URL of the server to which form field input information is sent. This attribute can specify a CGI or LiveWire application on the server; it can also be a mailto: URL if the form is to be mailed. See the location object for a description of the URL components. You can access this value using the action property.

METHOD=GET | POST specifies how information is sent to the server specified by ACTION. GET (the default) appends the input information to the URL, which on most receiving systems becomes the value of the environment variable QUERY_STRING. POST sends the input information in a data body, which is available on stdin with the data length set in the environment variable CONTENT_LENGTH. If the METHOD attribute has the value "POST," then the ENCTYPE attribute typically has the value "application/x-www-form-urlencoded." You can access this value using the method property.

ENCTYPE="encodingType" specifies the MIME encoding of the data sent: "application/x-www-form-urlencoded" (the default) or "multipart/form-data." Use "multipart/form-data" if the form contains a file upload element (INPUT TYPE="file"). If the METHOD attribute has the value "POST," then the ENCTYPE attribute typically has the value "application/x-www-form-urlencoded." You can access this value using the encoding property.

Syntax
To use a Form object's properties and methods:

1. formName.propertyName
2. formName.methodName(parameters)
3. forms[index].propertyName
4. forms[index].methodName(parameters)
ну да.. я собственно document.forms и имелл ввиду... :) сорри.. не достмотрел в первом посте kruglov'а этот момент.. но он потом правильно написал... так что что касаемо стандарта, то document.forms['formName'] будет правильным!
 

kruglov

Новичок
bkonst
Там чуть дальше

You can refer to the forms in your code by using the forms array (you can also use the form name)

и

Additionally, the document object has a separate property for each named form
 

bkonst

.. хочется странного?...
Угу-угу. До меня уже дошло, забыл, что объекты в JavaScript рассматриваются сразу и как ассоциативные массивы.
 
Сверху