奇怪的IE错误 - 在JavaScript全局变量和具有name属性的元素之间 [英] Strange IE error - between JavaScript global variable and element with name attribute

查看:108
本文介绍了奇怪的IE错误 - 在JavaScript全局变量和具有name属性的元素之间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在IE6,IE7和IE8中测试了以下代码,结果相同:

I tested the following code in IE6, IE7 and IE8 with the same result:


< a name =cd/> a< / a>

< script>

try {

cd = new Date;

} catch(e){

alert(e);

}

< / script>

在所有情况下都会引发错误。但是使用

In all cases an error is thrown. However using


var cd = new Date;

var cd = new Date;

似乎解决了这个问题。

有谁知道为什么会这样?

seems to solve the problem.
Does anyone know why that is ?

以下是一个例子: http://jsbin.com/ahuhu4/2

推荐答案

如果不使用var说明符来声明变量,则将变量cd作为属性添加到窗口对象,例如 window.cd 。您已经有一个对象元素,该对象元素是已经键入的< a name =cd> a< / a> 的窗口的子元素。您不能将新Date指定为此对象的类型,因为它已存在。使用var关键字时,您将该变量重新调整为局部范围并删除其对窗口对象的直接附件。这将删除错误并允许IE继续。其他浏览器引擎处理的方式不同。

When you don't use the var specifier to declare your variable, the variable cd is added as a property to the window object, e.g. window.cd. You already have an object element that is a child of window that is <a name="cd">a</a> which is already typed. You can't specify new Date as a type for this object as it already exists. When you use the var keyword, you are rescoping the variable to a local scope and removing its direct attachment to the window object. This removes the error and allows IE to proceed. Other browser engines handle this differently.

这篇关于奇怪的IE错误 - 在JavaScript全局变量和具有name属性的元素之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆