Javascript 错误:无法读取未定义的属性“替换”

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

Error : Cannot read property 'replace' of undefined

javascriptjquery

提问by Ridho Fauzan

I have javascript code and got an error Cannot read property 'replace' of undefined. Can anyone please help me to solve this? This is my code, and I currently using jQuery 2.1.3.

我有 javascript 代码并收到错误无法读取 undefined 的属性“替换”。任何人都可以帮我解决这个问题吗?这是我的代码,我目前使用 jQuery 2.1.3。

ExpandableTable.prototype.updateInputBoxName=function(){
    $("."+this.cloneClass,this.target).each(function(j,t){
        var n=j+1;
        $("input,textarea",$(t)).each(function(i,v){
            if($(v).attr("name")!=""){
                var newName=$(v).attr("name").replace(/\d+$/,"")+n;
                $(v).attr("name",newName);
            }
        });
    });
    return this
};
ExpandableTable.prototype.updateInputBoxId=function(){
    var t=this;
    $("."+t.cloneClass,this.target).each(function(j,u){
        var n=j+1;
        $("input,textarea",$(u)).each(function(i,v){
            if($(v).attr("id")!=""){
                var newId=$(v).attr("id").replace(/\d+$/,"")+n;
                $(v).removeAttr("id").attr("id",newId);
            }
        });
    });
    return this
};

it says i have an error on .replace.

它说我在.replace上有错误。

Please help me to solve this

请帮我解决这个问题

采纳答案by DGS

Your if statement needs to check that $(v).attr("id")is not undefined

您的 if 语句需要检查$(v).attr("id")是否未定义

  if ($(v).attr("id") != "" && typeof $(v).attr("id") != 'undefined') {

Should stop that error.

应该停止那个错误。

As MinusFour said if ($(v).attr("id"))is less verbose and achieves the same thing.

正如 MinusFour 所说if ($(v).attr("id"))的那样不那么冗长并实现了同样的事情。