javascript - 未捕获的类型错误 : Cannot call method 'toString' of null

标签 javascript getelementbyid getattribute

我正在尝试在 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/

相关文章:

JavaScript:根据输入字段值将查询字符串添加到 URL(如果设置)?

java - 如何在 selenium Web 驱动程序中获取跨度类值的属性

javascript - Angular JS 错误 - http ://errors. angularjs.org/1.5.0/$injector/unpr?p0

javascript - 在 React-Three-Fiber 中渲染索引缓冲区几何

javascript - ClearInterval 没有停止

JavaScript:获取下拉列表的值

java - 如何使用请求 getAttribute java 获取 boolean 值?

Python:如何从 __getattribute__ 方法访问属性

javascript - 应用程序按需发送 JSON,而不是创建时发送 JSON (Ext-JS 4)

javascript - Jsp 测验临时保存响应