使用Javascript获取HTML数组长度 [英] Getting HTML array length with Javascript
问题描述
当用户双击选择框中的元素时,我会动态创建输入。每个元素类型可以有多个输入,所以我将它们创建为HTML数组。创建输入时,还会创建指向javascript函数的链接。该功能将为点击的特定字段打开日历提示。我已经将问题缩小到了下面的代码:
document.getElementById('start_'+ field +'[]') .length
正如你所看到的,我试图抓住数组的长度,就像我会一个正常的javascript数组。这当然不起作用。我无法在Google上找到任何涉及这一点的内容,这通常意味着它是不可能的,但我觉得很难相信。
或者,每次创建该字段时,我都可以增加一个变量。我只是想确保我不会错过显而易见的东西。
预先感谢您!
{EDIT}
请参考 http://www.thefutureoftheweb.com/blog/use-arrays-with- HTML格式输入之前告诉我,HTML不允许数组。
{DoubleEdit + Answer}
问题不在于HTML数组不存在,而是ID属性不能是数组。我发现 http://roshanbh.com .np / 2008/08 / handling-array-html-form-elements-javascript-php.html ,它解释了如何做我需要的东西...... ish。
oForm = document者,恕不[0];
oForm.elements ['start_'+ field +'[]']。length;
或者在jQuery库中:
$('input [name =start_'+ field +'[]]')。length;
我更喜欢第二个,因为我不是100%确定第一个解决方案的跨浏览器兼容性。
I am dynamically creating inputs when the users double clicks an element in a select box. There can be multiple inputs per element type, so I am creating them as HTML arrays. When the inputs are created, a link is also created that points to a javascript function. Said function will open a calendar prompt for the specific field that was clicked. I have narrowed down the issue to the below code:
document.getElementById( 'start_' + field + '[]' ).length
As you see, I am trying to grab the length of the array just like I would with a normal javascript array. This, of course, is not working. I am unable to find anything on Google referencing this, which usually means it is impossible but I find that hard to believe.
Alternatively, I can increment a variable every time this field is created I just wanted to make sure I am not missing something painfully obvious.
Thank you in advance!
{EDIT}
Please reference http://www.thefutureoftheweb.com/blog/use-arrays-with-html-form-inputs before telling me that HTML does not allow arrays.
{DoubleEdit+Answer}
The issue was not that HTML arrays do not exist, but that the ID attribute cannot be an array. I found http://roshanbh.com.np/2008/08/handling-array-html-form-elements-javascript-php.html which explains how to do what I need...ish.
You can use the following pure JavaScript code:
oForm = document.forms[0];
oForm.elements['start_' + field + '[]'].length;
Or in jQuery library:
$('input[name="start_' + field + '[]"]').length;
I would prefer the second because I am not 100% sure about cross-browser compatibility of the first solution.
这篇关于使用Javascript获取HTML数组长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!