javascript 未捕获的类型错误:无法读取未定义的属性“substr”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26194238/
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 read property 'substr' of undefined
提问by Nikita
The problem is, I have worked on the script jquery.min.js version 1.4. After had to upgrade to version 1.9.1, and there was a problem.
问题是,我已经在脚本 jquery.min.js 1.4 版上工作了。之后不得不升级到1.9.1版本,出现了问题。
Uncaught TypeError: Can not read property 'substr' of undefined.
Tell me what to do. This part of the code in which the error occurred.
告诉我该怎么做。发生错误的这部分代码。
var processCaption = function(settings){
var nivoCaption = $('.nivo-caption', slider);
if(vars.currentImage.attr('title') != ''){
var title = vars.currentImage.attr('title');
if(title.substr(0, 1) == '#') title = $(title).html();
if(nivoCaption.css('display') == 'block'){
nivoCaption.find('p').fadeOut(settings.animSpeed, function(){
$(this).html(title);
$(this).fadeIn(settings.animSpeed);
});
} else {
nivoCaption.find('p').html(title);
}
nivoCaption.fadeIn(settings.animSpeed);
} else {
nivoCaption.fadeOut(settings.animSpeed);
}
}
回答by Tushar Gupta - curioustushar
Try
尝试
Soultion
灵魂
$.trim()will return empty string if it is undefined
or it has only whitespace
.
$.trim()将返回空字符串,如果它是undefined
或它只有whitespace
。
if($.trim($('#abc').attr('title')) != ''){
Problem
问题
if vars.currentImage.attr('title')
doesn't have title attribute will return undefined
not ''
(empty string) . And you are checking for empty string so it goes inside the loop if it doesn't have title attribute
如果vars.currentImage.attr('title')
没有 title 属性将返回undefined
not ''
(empty string) 。并且您正在检查空字符串,因此如果它没有标题属性,它就会进入循环
So you get error because substr
can only be applied to string
.
所以你会得到错误,因为substr
只能应用于string
.
回答by Basheer AL-MOMANI
check the variable for nullbefore calling substr()
在调用之前检查变量是否为空substr()
if (val1 != null) {
var val2= val1.substr(6);
//......
}