javascript 未捕获的类型错误:无法调用 null 的方法“toString”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13973094/
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
Uncaught TypeError: Cannot call method 'toString' of null
提问by Toni Cesar A. Amaral
I'm trying to create a class in JavaScript to validate a form. That'll check the form elements and validate a field if it has a specific attribute.
我正在尝试在 JavaScript 中创建一个类来验证表单。这将检查表单元素并验证字段是否具有特定属性。
However, the call to getAttribute
isn't returning a value. It doesn't get the value inside another variable, but, if I print, it works well.
但是,调用getAttribute
没有返回值。它不会在另一个变量中获取值,但是,如果我打印,它运行良好。
Here's the code for my class:
这是我班级的代码:
function valida() {
document.getElementById("msgDiv").innerHTML="";
var totalErros=0;
var x=document.getElementById("frm1");
for (var i=0;i<x.length;i++){
var input=document.getElementsByTagName("input")[i];
var campo=input.getAttribute("id");
var tipo=input.getAttribute("tipo");
var nome=input.getAttribute("nome");
var id=campo.toString(); //the error goes here
//var valor=_$(id).value;
alert(campo);
switch (tipo) {
case "obrigatorio":
if(document.getElementById(id).value==""){
document.getElementById("msgDiv").innerHTML+="Deu erro no campo "+nome+"<br />";
totalErros++;}
break
case "oemail":
if(document.getElementById(id).value==""){
document.getElementById("msgDiv").innerHTML+="Deu erro no campo "+nome+"<br />";
totalErros++;}
break
case "email":
if(!ValidaEmail(document.getElementById(id).value)){
document.getElementById("msgDiv").innerHTML+="O "+nome+" que você informou é inválido "+document.getElementById(id).value+" <br />";
totalErros++;}
break
default:
document.getElementById("msgDiv").innerHTML+="<br />";
}
}
if(totalErros==0) {
document.getElementById("msgDiv").innerHTML="Agora foi "+ totalErros;
return true;
}
}
回答by Levi Botelho
Your problem is this:
你的问题是这样的:
var input=document.getElementsByTagName("input")[i];
var campo=input.getAttribute("id");
//...
var id=campo.toString(); //the error goes here
You are getting a given input element and storing it in the variable input
. You are then getting the ID of that element and storing it in the variable campo
. You then take campo
and call toString() on it.
您正在获取给定的输入元素并将其存储在变量中input
。然后您将获得该元素的 ID 并将其存储在变量中campo
。然后你campo
在它上面调用并调用 toString() 。
The problem is that at least one input element does not have an ID. Because you cannot call toString
on null
, you get an error.
问题是至少有一个输入元素没有 ID。因为你不能叫toString
上null
,你会得到一个错误。
You don't actually need to call toString()
in the first place. Simply use campo
as is. It will either be null (if there is no ID) or a string.
您实际上并不需要首先调用toString()
。只需campo
按原样使用。它将为空(如果没有 ID)或字符串。
回答by Ja?ck
This part of your code piqued my curiosity:
这部分代码激起了我的好奇心:
var x=document.getElementById("frm1");
for (var i=0;i<x.length;i++){
var input=document.getElementsByTagName("input")[i];
This takes the collection of all<input>
elements on your page and takes the i
th one each time; and who knows what input element you may get.
这需要页面上所有<input>
元素的集合,并且每次都获取i
第一个;谁知道你会得到什么输入元素。
If you just want to traverse only the elements of the form you're interested in, this is much easier and faster:
如果您只想遍历您感兴趣的表单元素,这会更容易和更快:
var x = document.getElementById('frm1'),
input,
campo;
for (var i = 0, n = x.length; i != n; ++i) {
input = x.elements[i];
if (campo = input.id) {
// rest of your code
}
}
As you can see, I take the id
property instead of the id
attribute; this is generally a better thing to do, because changes in properties may not always be reflected in the respective attribute.
如您所见,我取的是id
属性而不是id
属性;这通常是更好的做法,因为属性的变化可能并不总是反映在相应的属性中。
Also, the .toString()
is superfluous, it's already a string if not null.
此外,.toString()
是多余的,如果不为空,它已经是一个字符串。
Update
更新
As @bfavaretto pointed out in the comment section, this part of your code could also be simplified:
正如@bfavaretto 在评论部分指出的,这部分代码也可以简化:
if(document.getElementById(id).value==""){
to this:
对此:
if (input.value == '') {
That would work whether the input element has an id or not
无论输入元素是否具有 id,这都有效