变量为null或未定义时出现IE9 javascript错误
我有一个文本区,在这里我使用javascript检查是否有写在上面的内容:变量为null或未定义时出现IE9 javascript错误,javascript,internet-explorer,cross-browser,Javascript,Internet Explorer,Cross Browser,我有一个文本区,在这里我使用javascript检查是否有写在上面的内容: if (!editorInstance.document.getBody().getChild(0).getText()) { do some action } 它在firefox上运行良好,但在IE9中,我收到一个错误,告诉我它是一个空的或未定义的对象(所以IE不会检查我的条件)。 所以我试着: var hasText = editorInstance.document.getBody().getChild(
if (!editorInstance.document.getBody().getChild(0).getText()) {
do some action
}
它在firefox上运行良好,但在IE9中,我收到一个错误,告诉我它是一个空的或未定义的对象(所以IE不会检查我的条件)。
所以我试着:
var hasText = editorInstance.document.getBody().getChild(0).getText();
if (typeof hasText === 'undefined') {
do some action
}
问题是它仍然在第一行停止(var hasText=edit…
),因为editorInstance.document.getBody().getChild(0).getText()返回null或未定义
编辑
当我执行editorInstance.document.getBody().getChild(0.getText()
时,我会在textarea中输入所有文本,但当没有输入文本时(我检查它以验证此字段),此代码不会返回任何内容,这就是为什么hasText
变量没有按我预期的方式工作的原因
知道如何解决它吗?您需要检查所引用的每个变量和函数结果是否存在
var firstChild = editorInstance && editorInstance.document && editorInstance.document.getBody() && editorInstance.document.getBody().getChild(0);
if (!firstChild || firstChild.getText() === '') {
// do some action
}
&&
是Javascript的。对于这样的情况,当您想要获取对象的值,但对象本身可能是null或未定义的时,它非常方便
考虑以下陈述:
var doc = editorInstance && editorInstance.document;
它的意思和
var doc;
if (editorInstance) {
doc = editorInstance.document;
} else {
doc = editorInstance;
}
但是它比较短。如果
editorInstance
为null您需要检查引用的每个变量和函数结果是否存在,则此语句不会出错
var firstChild = editorInstance && editorInstance.document && editorInstance.document.getBody() && editorInstance.document.getBody().getChild(0);
if (!firstChild || firstChild.getText() === '') {
// do some action
}
function test() {
var editor_val1 = CKEDITOR.instances.id1.document.getBody().getChild(0).getText() ;
var editor_val2 = CKEDITOR.instances.id2.document.getBody().getChild(0).getText() ;
var editor_val3 = CKEDITOR.instances.id3.document.getBody().getChild(0).getText() ;
if ((editor_val1 == '') || (editor_val2 == '') || (editor_val3 == '')) {
alert('Editor value cannot be empty!') ;
return false ;
}
return true ;
}
&&
是Javascript的。对于这样的情况,当您想要获取对象的值,但对象本身可能是null或未定义的时,它非常方便
考虑以下陈述:
var doc = editorInstance && editorInstance.document;
它的意思和
var doc;
if (editorInstance) {
doc = editorInstance.document;
} else {
doc = editorInstance;
}
但是它比较短。如果
editorInstance
为null它告诉您的是哪个部分为null?可能body
没有子项?可能editorInstance
本身为null?对不起。。我将编辑问题您仍然没有向我们显示错误消息。它告诉您的是哪一部分为空?可能正文
没有子项?可能编辑实例
本身为空?抱歉。。我将编辑问题您仍然没有向我们显示错误消息。
function test() {
var editor_val1 = CKEDITOR.instances.id1.document.getBody().getChild(0).getText() ;
var editor_val2 = CKEDITOR.instances.id2.document.getBody().getChild(0).getText() ;
var editor_val3 = CKEDITOR.instances.id3.document.getBody().getChild(0).getText() ;
if ((editor_val1 == '') || (editor_val2 == '') || (editor_val3 == '')) {
alert('Editor value cannot be empty!') ;
return false ;
}
return true ;
}