简体   繁体   English

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

[英]IE9 javascript error when variable is null or undefined

I have a textarea where I use javascript to check if there's something writen on it: 我有一个textarea,我在其中使用javascript来检查是否有写东西:

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

It works fine for firefox, but in IE9 I get this error telling it's a null or undefined object (so IE doesnt check my condition). 对于Firefox,它工作正常,但是在IE9中,我收到此错误,告诉它是空值或未定义的对象(因此IE不检查我的情况)。 so I tried: 所以我尝试了:

var hasText = editorInstance.document.getBody().getChild(0).getText();
if (typeof hasText === 'undefined') {
    do some action
}

The problem is that it still stops in the first line ( var hasText = edit... ), because the editorInstance.document.getBody().getChild(0).getText() returns null or undefined 问题在于它仍然停留在第一行( var hasText = edit... ),因为editorInstance.document.getBody().getChild(0).getText()返回null或未定义

EDIT 编辑

when I do editorInstance.document.getBody().getChild(0).getText() , I get all text entered in the textarea, but when there's no text entered (I check it to validate this field), this code returns nothing, this is why the hasText variable is not working the way I expected. 当我执行editorInstance.document.getBody().getChild(0).getText() ,我得到了在textarea中输入的所有文本,但是当没有输入任何文本时(我检查以验证此字段),此代码不返回任何内容,这就是为什么hasText变量无法按我预期的方式工作的原因。

Any idea about how can I solve it? 关于如何解决的任何想法?

You need to check for the presence of each variable and function result that you refer to. 您需要检查所引用的每个变量和函数结果是否存在。

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

&& is Javascript's logical AND operator . &&是Javascript的逻辑AND运算符 It's very handy for cases like this, when you want to fetch an object's value, but the object itself might be null or undefined . 当您想获取对象的值,但是对象本身可能为nullundefined时,这种情况非常方便。

Consider the following statement: 考虑以下语句:

var doc = editorInstance && editorInstance.document;

It means the same as 它的含义与

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

but it's shorter. 但更短。 This statement will not error out if editorInstance is null . 如果editorInstancenull ,则此语句不会出错。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM