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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 02:52:10  来源:igfitidea点击:

getElementByName returns Type Error?

javascriptcheckedunchecked

提问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 getElementsByNamewhich 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

getElementsByNamereturns an array of all elements with the given name. You either need to use the getElementByIdfunction 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.

您会收到“类型错误”,因为您正在检查是否检查了数组而不是特定元素。