You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何判断qrIndicator未定义仍出现Cannot read properties of null错误?

问题原因及解决办法

原因分析

你用var qrIndicator = document.getElementById("qr-indicator");声明了变量,不管页面里有没有这个元素,变量qrIndicator本身都是已定义的(不会是undefined)。当元素不存在时,document.getElementById会返回null,所以你写的typeof qrIndicator !== 'undefined'这个判断永远为真,代码依然会执行qrIndicator.style.display = "none",自然就触发了“无法读取null的style属性”的错误。

解决办法

把判断条件改成检查变量是否为null(或者直接利用真值判断):

if (qrIndicator) {
    qrIndicator.style.display = "none";
}

或者更严谨的写法:

if (qrIndicator !== null) {
    qrIndicator.style.display = "none";
}

另外,你那行try{...}finally{};完全没必要,document.getElementById本身不会抛出异常,直接写var qrIndicator = document.getElementById("qr-indicator");就行。

内容的提问来源于stack exchange,提问作者Vicente Chomali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 03:44:55