Javascript IndexOf 不适用于表单数组
为什么控制台会出现以下情况?或者我滥用了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
How come the following happens in the console? or am i misusing the 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Document.forms 是一个集合。如果您想要表格的编号(如您的评论中所示),那么问题仍然存在:您在哪一刻想要该编号?无论如何,您可以创建一个表单数组:
现在您有一个包含对所有表单的引用的数组,并且对于每个表单,都有一个索引值,该索引值反映您通过其 id 为其提供的表单编号。因此:
formsArray[0]
包含对forms['form-0']
的引用,formsArray[1]
对forms[ 'form-1']
等Document.forms is a collection. If you want the number of a form - as indicated in your comments -, the question remains: at which moment do you want that number? Anyway, you could create an array of forms:
Now you have an Array containing references to all forms, and for each form an index value that reflects the form number you gave it via it's id. So:
formsArray[0]
contains a reference toforms['form-0']
,formsArray[1]
toforms['form-1']
etc.您使用了错误的语法...indexOf 是一种方法,因此它应该使用括号,而不是方括号。
对于对象,您可以简单地使用括号请求该对象:
You've used the wrong syntax... indexOf is a method, so it should use parenthesis, not brackets.
With an object, you can simply request the object using brackets:
document.forms
是一个HTMLCollection
。它不是一个数组。因此,它没有indexOf
方法。您可以使用 Array.prototype.slice.call 对其进行转换:
但是请注意,并不普遍支持
indexOf
。然而,我不完全确定你想要做什么,所以无论如何,这很可能不是必要的方法。document.forms
is anHTMLCollection
. It is not an array. As such, it does not have anindexOf
method.You can convert it using
Array.prototype.slice.call
:Note, however, that
indexOf
is not universally supported. I'm not entirely sure what you're trying to do, however, so it may well not be the necessary approach anyway.如果您尝试通过 ID 获取元素,只需直接使用 ID 即可。
如果你想要它的索引,看起来你已经在 ID 中拥有它了。只需删除
"form-"
部分即可。或者,如果您有该元素,请通过其 ID 属性执行相同操作:
If you're trying to get the element by its ID, just use the ID directly.
If you want its index, it would seem that you already have it in the ID. Just remove the
"form-"
part.Or if you have the element, do the same via its ID property:
如果您想使用 javascript 访问表单的元素,那么您必须使用:document.myform.elements[i],其中 i 是元素的位置。您可以参考这个Javascript表单对象 - 属性和方法教程。 indexof 是 javascript 字符串对象的方法。
If you want to access the elements of a form using javascript, then you have to use this: document.myform.elements[i], where i is the position of the element. You may refer this Javascript Form Objects - Properties and Methods tutorial. indexof is a method of javascript string object.