这是一个两部分的问题。有人几天前回答了一个类似的问题(其中也包含了关于PHP中这种类型数组的信息),但我找不到它。
1.) 首先,对于表单中在名称元素末尾创建的数组,什么是正确的术语?
<form>
<input name="p_id[]" value="0"/>
<input name="p_id[]" value="1"/>
<input name="p_id[]" value="2"/>
</form>
2.) 如何使用JavaScript从该数组中获取信息?具体而言,我现在只想计算数组的元素个数。这是我做的,但它不起作用。
function form_check(){
for(var i = 0; i < count(document.form.p_id[]); i++){ //Error on this line
if (document.form.p_name[i].value == ''){
window.alert('Name Message');
document.form.p_name[i].focus();
break;
}
else{
if (document.form.p_price[i].value == ''){
window.alert('Price Message');
document.form.p_price[i].focus();
break;
}
else{
update_confirmation();
}
}
}
}
for(i = 0; i < document.form.elements['p_id[]'].length; i++)
- ubiquibaconi
作为全局变量使用并不是一个好主意(这只会让你遇到范围问题,无论是现在还是将来,因为你已经养成了不良习惯)。使用document.form
是一种不好的做法,因为(a)document.forms
集合会更清晰地表明你正在做什么,form
不是一个非常详细的名称(而且document.form
可能会与document.forms
混淆,这会使维护更加混乱)。将代码压缩到单行中是可以的,但我只是更加明确地阐述了一下,以便你可以看到发生了什么。 - Quentinfor (var i...)
实际上与var i; for (i ...)
相同,因为JavaScript变量是函数作用域,而不是像许多流行的面向对象语言一样块作用域。 - Laoujinvar i; for (i...)
。 - Quentin