我有JavaScript代码,但出现错误无法读取未定义的属性“替换”。谁能帮我解决这个问题?这是我的代码,目前使用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
};
它说我在.replace上有错误。
请帮我解决这个问题
最佳答案
您的if语句需要检查$(v).attr("id")
是否未定义
if ($(v).attr("id") != "" && typeof $(v).attr("id") != 'undefined') {
应该停止该错误。
正如MinusFour所说,
if ($(v).attr("id"))
不太冗长,并且实现了相同的目的。