javascript getElementsByName() 返回未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20438797/
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
getElementsByName() returns undefined
提问by user3076979
here is my basic code. I just need to print the value entered by the user. However, it returns undefined. Please help. Thanks in advance.
这是我的基本代码。我只需要打印用户输入的值。但是,它返回未定义。请帮忙。提前致谢。
Script
脚本
// using getElementsByName() method
function msg(){
var v=document.getElementsByName("name1");
alert("Your name is:"+v[0].innerHTML);
}
HTML
HTML
<input type="text" name="name1"/>
<input type="button" value="Submit" onclick="msg()"/>
回答by Sergio
Use .value
, instead of .innerHTML
...
使用.value
, 而不是.innerHTML
...
.getElementsByName()
returns what you expect, your problem is the (miss)use of innerHTML
.
.getElementsByName()
返回您期望的内容,您的问题是(错过)使用innerHTML
.
// using getElementsByName() method
function msg() {
var v = document.getElementsByName("name1");
alert("Your name is:" + v[0].value);
}
Fiddle
小提琴
回答by BSnapZ
I just ran your code, and it doesn't appear to return undefined. In fact, your getElementsByName returns the correct object. The problem is your alert statement.
我刚刚运行了你的代码,它似乎没有返回 undefined。事实上,您的 getElementsByName 返回正确的对象。问题在于您的警报声明。
You have:
你有:
alert("Your name is:"+v[0].innerHTML);
Should be:
应该:
alert("Your name is:"+v[0].value);
回答by Krish R
Try to use value
instead of innerHTML
尝试使用value
代替innerHTML
document.getElementsByName()
returns an HTMLCollectionof all the elements with a given value for the name attribute.
document.getElementsByName()
返回具有给定 name 属性值的所有元素的HTMLCollection。
So use like alert("Your name is:"+v[0].value);
所以使用像 alert("Your name is:"+v[0].value);
Ref: https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByName
参考:https: //developer.mozilla.org/en-US/docs/Web/API/document.getElementsByName
回答by Chetan hada
use this code
使用此代码
<script>
function msg(){
var v=document.getElementsByName("name1");
alert(v);
alert("Your name is:"+v[0].value);
}
</script>