我有一个文本区域,我在其中使用 JavaScript 来检查上面是否写有内容:
if (!editorInstance.document.getBody().getChild(0).getText()) {
do some action
}
它在 Firefox 中工作正常,但在 IE9 中我收到此错误,告诉它是一个 null 或 undefined object (因此 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()
时,我得到了在文本区域中输入的所有文本,但是当没有输入文本时(我检查它以验证此字段),此代码不返回任何内容,这就是 hasText
变量未按我预期的方式工作的原因。
知道如何解决这个问题吗?
最佳答案
您需要检查您引用的每个变量和函数结果是否存在。
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 或 未定义时,这非常方便。
考虑以下语句:
var doc = editorInstance && editorInstance.document;
意思是一样的
var doc;
if (editorInstance) {
doc = editorInstance.document;
} else {
doc = editorInstance;
}
但它更短。如果 editorInstance
为 null,此语句不会出错。
关于javascript - 当变量为 null 或未定义时 IE9 javascript 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14054651/