我有一段JavaScript,它是库的一部分,我希望只有在某个框架集可用时才启用它。
我想做的就是:
if (typeof(top.TableOfContents.frames.content)!=='undefined') {
// stuff I want to do only if there's a frame named
// TableOfContents with a frame named content
}现在,如果帧不可用,我会收到错误,所以我现在要做的是:
if (typeof(top.TableOfContents)!=='undefined'
&& typeof(top.TableOfContents.frames)!=='undefined'
&& typeof(top.TableOfContents.frames.content)!=='undefined'){
// stuff I want to do only if there's a frame named
// TableOfContents with a frame named content
}但感觉上可能有更好的方法来做到这一点(除了丢失帧,哈哈)……有没有一种更有效或更少冗长的方法来测试对象和子对象和子对象?
现在,这些都是用相对urls引用的框架,所以应该没有我能想到的"same origin policy“问题(我在测试中没有遇到任何问题)。
发布于 2010-10-08 22:14:56
在这种情况下我喜欢用筛子。
if (!!((((top || {}).TableOfContents || {}).frames || {}).content)) {
// stuff you want to do only if there's a frame named
// TableOfContents with a frame named content
}double not (!!)进行显式布尔型转换。
这与您已经在做的控制相同(没有更多),但效率更高
https://stackoverflow.com/questions/3891303
复制相似问题