[英]getElementsByName won't loop through entire array
The following code executes on the press of a button. 按下按钮即可执行以下代码。 It works fine alerting one string of the getElementsByName array, but when introduced to a loop, it still only alerts the first string value, and nothing more:
它可以很好地警告getElementsByName数组的一个字符串,但是当引入循环时,它仍然仅警告第一个字符串值,仅此而已:
function checkvals() {
var input = document.getElementsByName('ModuleTitle', 'ModuleCode', 'BuildingName', 'Day');
var i = 0;
for (i = 0; i <= input.length; i++){
alert(input[i].value);
}
}
That's because getElementsByName
only accepts one argument, so it's only fetching the first name. 那是因为
getElementsByName
只接受一个参数,所以它只获取第一个名字。
You can build a full collection like this... 你可以像这样构建一个完整的集合......
var names = ['ModuleTitle', 'ModuleCode', 'BuildingName', 'Day'];
var input = [];
for(var i = 0; i < names.length; i++) {
var name_els = document.getElementsByName(names[i]);
for(var j = 0; j < name_els.length; j++) {
input.push(name_els[j]);
}
}
Then loop over the input
Array, (or just do your work in the inner loop) . 然后遍历
input
数组, (或者只是在内部循环中完成工作) 。
Additionally, you have a bug. 此外,您还有一个错误。
This... 这个...
for (i = 0; i <= input.length; i++){
should be this... 应该是这个...
for (i = 0; i < input.length; i++){
...otherwise, you'll go one past the last index. ...否则,你会超过最后一个索引。
That's because getElementsByName
only takes a single name
argument, and returns all elements with that value for their name
attribute. 这是因为
getElementsByName
只需要一个 name
的说法,并为他们的那个值返回的所有元素name
属性。 (See https://developer.mozilla.org/en/DOM/document.getElementsByName .) If you have multiple name
s to look up, you'll have to call it multiple times. (请参阅https://developer.mozilla.org/en/DOM/document.getElementsByName 。)如果要查找多个
name
,则必须多次调用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.