变量为null或未定义时IE9 javascript错误

时间:2012-12-27 12:23:22

标签: javascript internet-explorer cross-browser

我有一个textarea,我使用javascript来检查是否有写的内容:

if (!editorInstance.document.getBody().getChild(0).getText()) {
    do some action
}

它适用于firefox,但在IE9中我得到此错误告诉它是一个null或未定义的对象(因此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中输入所有文本,但是当没有输入文本时(我检查它以验证此字段),此代码不返回任何内容,这就是为什么{{1}变量不按我预期的方式工作。

关于如何解决它的任何想法?

2 个答案:

答案 0 :(得分:1)

您需要检查所引用的每个变量和函数结果是否存在。

var firstChild = editorInstance && editorInstance.document && editorInstance.document.getBody() && editorInstance.document.getBody().getChild(0);
if (!firstChild || firstChild.getText() === '') {
    // do some action
}

&&是Javascript的logical AND operator。对于这样的情况,当您想要获取对象的值时,它非常方便,但对象本身可能是 null undefined

请考虑以下声明:

var doc = editorInstance && editorInstance.document;

相同
var doc;
if (editorInstance) {
    doc = editorInstance.document;
} else {
    doc = editorInstance;
}

但它更短。如果editorInstance null ,则此语句不会出错。

答案 1 :(得分:0)

 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 ;
}