【发布时间】:2012-09-03 13:35:17
【问题描述】:
直接定义变量时,它可以工作。和下面的代码一样,body的背景色在IE中为浅绿色,在非IE浏览器中为浅蓝色。
<html>
<body>
<script>
if (window.attachEvent) {
var YourBrowserIsIE = true;
}
if (YourBrowserIsIE) {
document.body.style.backgroundColor = 'lightgreen';
}
else {
document.body.style.backgroundColor = 'lightblue';
}
</script>
</body>
</html>
但是,有时需要使用 eval() 定义变量,如下所示,但结果会显示错误,指出 YourBrowserIsIE 在非 IE 浏览器中未定义。
if (window.attachEvent) {
eval('var YourBrowserIsIE = true;');
}
是的,我知道我可以为非 IE 浏览器预定义 var YourBrowserIsIE = false; 或将 if 语句更改为 if (typeof YourBrowserIsIE != 'undefined'),但我希望尽可能减少代码。
那么有没有解决方案使用 eval() 定义变量并使用简单的if (YourBrowserIsIE) 检查变量而不在非 IE 浏览器中显示任何错误?
== 编辑 ==
抱歉,不清楚。上面提到的使用eval()的情况,其实是为了检测IE版本。请看以下代码。
<html>
<body>
<script>
if (window.attachEvent) {
var version = /msie (\d+)/i.exec(navigator.userAgent)[1];
eval('var YourBrowserIsIE' + version + ' = true;');
}
if (YourBrowserIsIE9) {
document.body.style.backgroundColor = 'lightgreen';
}
else {
document.body.style.backgroundColor = 'lightblue';
}
</script>
</body>
</html>
【问题讨论】:
-
不应该
YourBrowserIsIE在非 IE 浏览器中的两个代码中都未定义吗?只要window.attachEvent不存在,就永远不会定义YourBrowserIsIE。 -
var attachEvent在全球范围内怎么样?我的浏览器不一定是IE,但你的代码会这样对待。 -
你认为为什么需要
eval? -
谢谢大家,很抱歉不清楚。我已经编辑了这个问题。
-
你试过
window['YourBrowserIsIE' + version] = true;
标签: javascript variables eval undefined