JavaScript getElementByName 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2980830/
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
JavaScript getElementByName doesn't work
提问by Philip007
This simple JS can't set the value of "para". I guess getElementByName doesn't work. But why?
这个简单的JS无法设置“para”的值。我猜 getElementByName 不起作用。但为什么?
<script>
function fn()
{
document.getElementById("para").setAttribute("name","hi");
document.getElementByName("hi").setAttribute("value","my value is high");
}
</script>
HTML:
HTML:
<input type="button" onClick="fn()" value="click me">
<input id="para" type="text" />
回答by Matthew Flaschen
It's getElementsByName. Note the plural. It returns an array-like NodeList of elements with that nameattribute.
它是getElementsByName。注意复数。它返回具有该name属性的元素的类似数组的 NodeList 。
回答by Wrikken
getElementsByNameexists, which returns a collection of the elements. If you plan to find only one:
getElementsByName存在,它返回元素的集合。如果您打算只找到一个:
document.getElementsByName("hi")[0].setAttribute("value", "my value is high");
Edit: a, HTML there (didn't see that before the edit). No 'hi' element in HTML, possibly in some XML format there is...
编辑:a,HTML 那里(在编辑之前没有看到)。HTML 中没有 'hi' 元素,可能在某些 XML 格式中有...
回答by Jeaf Gilbert
not getElementByNamebut getElementsByName, and it returns array.
not getElementByNamebut getElementsByName,它返回数组。
<html>
<head>
<script language="javascript">
function fn() {
document.getElementById("para").setAttribute("name","hi");
x = document.getElementsByName("hi");
x[0].setAttribute("value","my value is high");
}
</script>
</head>
<body onload="fn()">
<input type="text" id="para" />
</body>
</html>
回答by Philip007
Also, i find that document type must be declared to make getelementsbyname work.
另外,我发现必须声明文档类型才能使 getelementsbyname 工作。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

