代码之家  ›  专栏  ›  技术社区  ›  nemesisdesign

IE8奇怪的行为,我的问题还是错误?

  •  0
  • nemesisdesign  · 技术社区  · 15 年前

    好了,伙计们,这很有趣,

    我正在测试这个页面

    http://static.nemesisdesign.net/demos/ie8-strange/test.html

    在IE8/Windows XP上。

    这是代码:

    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml" lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="content-language" content="en">
        <title>Test</title>
    </head>
    <body>
    <div id="thisgivesmeanerror">test</div>
    <script>
        thisgivesmeanerror = 'test';
        alert('this alert won\'t be fired on my IE8, what about yours?');
    </script>
    </body>
    </html>
    

    如果我用IE8打开这个页面,我会得到一个错误。 如果我将脚本的代码更改为:

    <script>
        // note that I added var prefix
        var thisgivesmeanerror = 'test';
        alert('this alert won\'t be fired on my IE8, what about yours?');
    </script>
    

    它工作得很好。 这只发生在IE7/8上,没有在IE6上测试。

    你怎么认为? 你也会这样吗?还是我的浏览器疯了?

    添加

    你是说这只是不使用导致错误的var前缀? 对不起,伙计们,你们错了,你们没花时间测试代码。

    我上传了一个测试2页面 http://static.nemesisdesign.net/demos/ie8-strange/test2.html 用下面的cocode

    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml" lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="content-language" content="en">
        <title>Test 2</title>
    </head>
    <body>
    <div id="thisgivesmeanerror">test</div>
    <script>
        thisdoesntgiveanyerror = 'test';
        alert('This alert will be fired correcly');
    </script>
    </body>
    </html>
    

    那很好。

    那么究竟是什么导致了这个错误呢?没有var前缀的变量名与div元素的id同名。

    这不奇怪吗?

    4 回复  |  直到 15 年前
        1
  •  2
  •   Community Mohan Dere    8 年前

    可能是答案 this SO-question 能帮忙吗?

        2
  •  1
  •   Darin Dimitrov    15 年前

    变量声明之前应始终使用 var 指定它们的作用域,否则您可能会发现不同浏览器之间的行为不一致。

        3
  •  0
  •   Ali Tarhini    15 年前

    使用 var 声明变量而不只是插入变量名

        4
  •  0
  •   Bojangles Vincent Baillet    15 年前

    我想说,IE中的javascript解释器比Firefox和其他浏览器中的解释器要严格一些,这意味着当涉及到变量定义行时,脚本会返回一个错误。放 var 在会确保它实际上 变量。

    var

    詹姆斯

    编辑

    我现在不能去,但我建议你换一下 <script> 标签到 <script type="text/javascript"> .