Javascript未定义错误,即使之前已检查
这是我的密码:Javascript未定义错误,即使之前已检查,javascript,jquery,Javascript,Jquery,这是我的密码: if (target && thisLastCell) { if (target.html() && thisLastCell.html()) { while( (target.html().length > 0 || target.hasClass('notop') || target.hasClass('event-cell') )
if (target && thisLastCell) {
if (target.html() && thisLastCell.html()) {
while(
(target.html().length > 0
|| target.hasClass('notop')
|| target.hasClass('event-cell')
)
||
(thisLastCell.html().length > 0
|| thisLastCell.hasClass('notop')
|| thisLastCell.hasClass('event-cell')
)
) {
// some more code
}
}
}
即使我之前用if(target&&thisLastCell){
和if(target.html()&&thisLastCell.html()){
根据注释编辑:目标定义为:
var target = $('#calendar-full tr#hour_'+sHour+'_'+tr+' td:nth-child('+colNum+')');
javascript控制台中的错误是:uncaughttypeerror:无法读取未定义的属性“length”
这怎么可能呢?如果
目标
没有定义,那么它仍然会抛出一个错误(我想是因为更严格的检查,不过不要引用我的话)。
如果您先将其包装在类型的
声明中,则它可以正常工作,例如
if (typeof(target) !== 'undefined' && thisLastCell) {
// rest of your code
}
我终于找到了答案。我得到的错误是因为我更改了
目标
代码和括号中的最后一个单元格
代码,这就是为什么上面的检查没有再检查的原因。提供了一个JSFIDLE链接?什么是未定义
?是变量吗?我想你可能会得到一个未定义的函数error、 请提供更多代码和/或完整错误。我无法在JSFIDLE中重复它,因为代码非常复杂。目标id jQuery选择:var target=$(“#日历完整tr#小时”+sHour+“#”+tr+”td:nth child(“+colNum+”)
请阅读以下内容:如果您自己无法在最短的时间内复制它,那么我们如何复制它?请尝试使用if(target.length&&thisLastCell.length)
,因为您的检查可能是true
,即使jQuery没有找到任何元素。这是错误的。布尔值(未定义)
为false,因此如果target
为“未定义”,则示例代码不会引发错误。var a=undefined;如果(a){}
未引发错误。True,但是if(target&&thisLastCell){}
确实会引发错误,可能是因为在您的示例中,a
仍然被声明,即使初始化为undefined?但根本没有target
的历史记录?当然,但我强烈认为target
已经声明。