如何设置“if object exists”?条件? [英] How do I setup an "if object exists" condition?
问题描述
有没有办法检查对象是否存在?我不断收到需要对象的错误。我知道该对象不存在,我想绕过我的代码的一部分,如果是这样的话。我不知道我还没有尝试过...
Is there some way to check if an object exists? I keep getting an "object required" error. I know the object does not exist and I would like to bypass a part of my code should that be the case. I don't know what I have not tried...
var codeName = document.getElementById('testCode');
//I have tried
if(codeName != null)
if(codeName.length != 0)
if(typeOf codeName != 'undefined')
if(!codeName)
if(codeName.value != null)
是否有查看对象是否存在的任何方法?
Is there any way to see if an object exists?
推荐答案
getElementById
之后call, codeName
是一个DOM元素或null。您可以使用警报查看哪个:
After the getElementById
call, codeName
is either a DOM Element or null. You can use an alert to see which:
alert(codeName);
所以 if(codename!= null)
应该工作。
错误是否会在它到达之前发生?我会尝试添加警报,以便在代码运行时查看值。或者在调试器中逐步执行此代码。
Does the error happen before it gets that far? I would try adding alerts to see the values as the code runs. Or step through this code in a debugger.
这篇关于如何设置“if object exists”?条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!