控制台中为什么会出现以下情况?还是我滥用了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发布于 2011-05-14 00:42:23
Document.forms是一个集合。如果你想要一个表单的编号- -正如你的comments -中所指出的那样,问题仍然存在:你在什么时候想要这个数字?无论如何,您可以创建一个表单数组:
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];
}
}现在,您有了一个数组,其中包含对所有表单的引用,并且对于每个表单,都有一个索引值,该值反映了您通过其id为其提供的表单编号。因此:formsArray[0]包含对forms['form-0']的引用,formsArray[1]对forms['form-1']等的引用。
发布于 2011-05-14 00:18:43
您使用了错误的语法...indexOf是一个方法,所以它应该使用圆括号,而不是方括号。
someString.indexOf("form-0")对于一个对象,您可以简单地使用方括号请求该对象:
document.forms["form-0"]发布于 2011-05-14 00:22:44
document.forms是一个HTMLCollection。它不是数组。因此,它没有indexOf方法。
您可以使用Array.prototype.slice.call对其进行转换
var formsArr = Array.prototype.slice.call(document.forms);但是,请注意,并不是所有人都支持indexOf。但是,我不能完全确定您想要做什么,所以这可能不是必要的方法。
https://stackoverflow.com/questions/5994802
复制相似问题