为何判断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
相关产品推荐
相关产品推荐

