使用eval()定义变量显示未定义的错误
Defining variable using eval() shows undefined error
当直接定义变量时,它是有效的。与下面的代码一样,在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浏览器中显示任何错误?
===EDIT===
抱歉说不清楚。上面提到的使用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>
但我想把代码保持在尽可能小的
那不是window.YourBrowserIsIE = window.attachEvent;
吗?
我看到它的两个优点:
- 它是最小的
- 它不需要
eval
看到你的代码,我建议根本不要使用YourBrowserIsIE
,而是使用:
document.body.style.backgroundColor = window.attachEvent
? 'lightgreen' : 'lightblue';
看到你的编辑,那可能是:
document.body.style.backgroundColor =
+((/msie ('d+)/i.exec(navigator.userAgent)||[0])[1]) === 9
? 'lightgreen' : 'lightblue';
如果它必须是一个可重复使用的变量,我会回到解决方案1:
window['YourBrowserIsIE'+((/msie ('d+)/i.exec(navigator.userAgent)||[0])[1]]
= true;
document.body.style.backgroundColor = window.YourBrowserIsIE9 ?
? 'lightgreen' : 'lightblue';
将else
案例置于if
条件下,然后尝试:
if (window.attachEvent) {
eval('var YourBrowserIsIE = true;');
}
else{
eval('var YourBrowserIsIE = false;');
}
由于您在if (window.attachEvent)
条件内声明变量YourBrowserIsIE
,因此如果上述条件失败,则该变量将保持未定义状态。
正如其他人所建议的那样,没有必要执行eval。
无论如何,如果您希望将代码设置为true/false;你可以执行这个
eval('var YourBrowserIsIE = window.attachEvent ? true : false;')
除非你分享实际问题,否则很难提供解决方案。
忽略使用对象推理是检测用户代理的一种严重缺陷的方法(许多浏览器复制IE的事件模型),因此非常不可靠,以下是如何在没有eval和最少代码的情况下完成您正在尝试的操作:
[…呃,请参阅Kooilnc的回答…]
- 敲除jsobservable显示未定义的值
- 使用eval()定义变量显示未定义的错误
- 当使用多个false时,Select2显示未定义
- 函数在控制台中显示“未定义”
- 在文本区域显示未定义的javascript数组
- this.value在<td>标记显示未定义
- Chrome 显示未定义密钥代码
- 节点.js 使用 Multer 上传图像显示未定义
- 语句的 Javascript 一直显示未定义
- 显示未定义值的工具提示
- 为什么它在数组之前显示未定义
- Ajax 结果显示未定义
- 显示“未定义”的 JS 警报
- 样式.在元素正确定义时显示未定义
- 它一直显示未定义的文件名
- jQuery每个函数和数组在for循环中显示未定义
- Hapi在处理程序中显示未定义的变量
- 选择2显示未定义
- Json数组只显示未定义的未定义
- 来自文本框和单选按钮的用户输入在警报中重复,显示未定义