Javascript 错误 - document.getElementsById 不是函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7885639/
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-26 01:38:38  来源:igfitidea点击:

Javascript error - document.getElementsById is not a function

javascript

提问by Rahul Singh

Since I am calling this code in loop. But following code is giving me error as document.getElementsByIdis not a function. What should I do how can I call doc.getbyid in loop.

因为我在循环中调用此代码。但是下面的代码给了我错误,因为document.getElementsById它不是一个函数。我应该怎么做如何在循环中调用 doc.getbyid。

for (var z=1; z < i; z++){
       var textbox = document.getElementsById("a"+z).value;
       var textbox2 = document.getElementsById("b").value;
       var textbox3 = document.getElementsById("c").value;
       alert(textbox);
       alert(textbox2);
       alert(textbox3);
}

回答by James Allardice

That's because it getElementById(note the lack of the "s" on "Element"). Which makes sense if you think about it, because idvalues have to be unique in a document, so there will be only one "element" that matches, rather than multiple "elements".

那是因为它getElementById(注意“元素”上缺少“s”)。如果您考虑一下,这是有道理的,因为id值在文档中必须是唯一的,因此只有一个“元素”匹配,而不是多个“元素”。

However, there are methods that return multiple elements which do use the plural "elements", such as getElementsByTagName, so you may just be mixing them up.

但是,有些方法会返回使用复数“元素”的多个元素,例如getElementsByTagName,因此您可能只是将它们混在一起。

回答by Merianos Nikos

The function is not getElementsById but getElementById.

该函数不是 getElementsById 而是 getElementById。

There is no plural form on Element

Element 上没有复数形式

回答by Unknown

Actually you need to use as follows:

其实你需要使用如下:

for (var z = 1; z < i; z++) { 
    var textbox = document.getElementById("a"+z).value; 
    var textbox2 = document.getElementById("b").value; 
    var textbox3 = document.getElementById("c").value; 
    alert(textbox); 
    alert(textbox2); 
    alert(textbox3); 
} 

回答by Dave Newton

The name of the function is getElementById.

该函数的名称是getElementById