控制台中如何发生以下情况?还是我滥用indexOf?

document.forms:

[
<form id=​"form-0" name=​"form-0">​…​</form>​
,
<form id=​"form-1" name=​"form-1">​…​</form>​
,
<form id=​"form-2" name=​"form-2">​…​</form>​
]

document.forms.indexOf["form-0"]:

TypeError: Cannot read property 'form-0' of undefined

最佳答案

Document.forms是一个集合。如果您想要表格的编号(如注释中所示),则问题仍然存在:您希望在哪个时刻使用该编号?无论如何,您可以创建一系列表单:

var allforms = document.getElementsByTagName('form'),
    formsArray = [];
for (var i=0;i<allforms.length;i++){
   if (allforms[i].id.match(/\d+$/)){
       var indexval = parseInt(allforms[i].id.replace(/(.+)(\d+)$/,'$2'),10);
       formsArray[indexval] = allforms[i];
   }
}


现在,您有了一个包含对所有表单的引用的Array,并且对于每个表单,都有一个索引值,该索引值反映了您通过其ID给它的表单编号。因此:formsArray[0]包含对forms['form-0']的引用,formsArray[1]forms['form-1']的引用等。

07-24 18:51
查看更多