我正在尝试在 JavaScript 中创建一个类来验证表单。这将检查表单元素并验证字段是否具有特定属性。
但是,对 getAttribute
的调用没有返回值。它没有获取另一个变量内的值,但是,如果我打印,它工作得很好。
这是我的类(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;
}
}
最佳答案
您的问题是这样的:
var input=document.getElementsByTagName("input")[i];
var campo=input.getAttribute("id");
//...
var id=campo.toString(); //the error goes here
您正在获取给定的输入元素并将其存储在变量input
中。然后,您将获取该元素的 ID 并将其存储在变量 campo
中。然后,您使用 campo
并对其调用 toString()。
问题是至少有一个输入元素没有 ID。因为您无法对 null
调用 toString
,所以您会收到错误。
您实际上并不需要首先调用toString()
。只需按原样使用 campo
即可。它要么为 null(如果没有 ID),要么为字符串。
关于javascript - 未捕获的类型错误 : Cannot call method 'toString' of null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13973094/