javascript getElementByName 返回类型错误?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15995124/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
getElementByName returns Type Error?
提问by jth41
My code:
我的代码:
var isSomethingChecked = (document.getElementByName("koalaCheck").checked ||
document.getElementByName("kangarooCheck").checked);
Why does this code throw an exception called "Type Error"?
为什么这段代码会抛出一个名为“类型错误”的异常?
回答by DiverseAndRemote.com
There is no function called getElementByName
. what you need is getElementsByName
which returns an array of all of the elements that have that name. so you can use:
没有调用的函数getElementByName
。您需要的是getElementsByName
返回具有该名称的所有元素的数组。所以你可以使用:
var isSomethingChecked = (document.getElementsByName("koalaCheck")[0].checked ||
document.getElementsByName("kangarooCheck")[0].checked);
回答by Daedalus
That would be because the correct method is document.getElementsByName()
. You missed an s.
那是因为正确的方法是document.getElementsByName()
. 你错过了一个s。
View the documentation.
查看文档。
Assuming you do not wish to check each checked state per element(as this method returns an array).. I would use document.getElementById()
.. but that is without seeing your html.
假设您不希望检查每个元素的每个检查状态(因为此方法返回一个数组)。我会使用document.getElementById()
.. 但那是没有看到您的 html。
回答by Alex Kalicki
getElementsByName
returns an array of all elements with the given name. You either need to use the getElementById
function or specify a particular element in the returned array like so:
getElementsByName
返回具有给定名称的所有元素的数组。您要么需要使用该getElementById
函数,要么在返回的数组中指定一个特定元素,如下所示:
var isSomethingChecked = (document.getElementsByName("koalaCheck")[0].checked || document.getElementsByName("kangarooCheck")[0].checked);
You get the "Type Error" because you are checking whether an array is checked instead of a particular element.
您会收到“类型错误”,因为您正在检查是否检查了数组而不是特定元素。