开发者

onclick="alert(ping.test);" gives undefined

<body>
   <script>
    ping = new Object;
    ping.test = '1234';
   </script>

<a href="#" onclick="alert(ping.test);">Test</a>
</body>

why is this working in IE8 but not in Firefox or chrome ? The popup gives "undefined" in FF v5 and Chrome v12 , it gives 开发者_运维百科"1234" in IE9.


This is the inline event model (DOM Level 0) so only variables defined within its execution context will be used.

The following section

ping = new Object;
ping.test = '1234';

is in its own execution context when the interpreter goes through the page. Code in global scope will use the global object via this.

But here

<a href="#" onclick="alert(ping.test);">Test</a>

is a separate execution, which your browser views as an anonymous function. Using

<a href="#" onclick="alert(this);">Test</a>

Will not result in what we want. The line sees window, the this is actually being used for the current object that the inline event handler works with.

So ping is not defined within this context unless we allow it to be seen by referring to window.

<a href="#" onclick="alert(window.ping.test);">Test</a>

Now when the browser runs, it will grab the window global variable which in the (\script\) context will be the same as this and have access to to ping.test

Seen in the following browsers

  • Google Chrome Mac 12.0.742.112
  • Safari Version 5.0.5 (6533.21.1)
  • Firefox Mac 3.6.18

References
Mozilla Docs: this keyword
Dom Events: inline model


ping has gone out of scope. Try this:

<body>
    <a href="#" id="test">Test</a>
    <script>
    var ping = new Object();
    ping.test = '1234';
    document.getElementById("test").onclick = function() { 
        alert(ping.test);
    };
    </script>
</body>


It's a scope issue. Try this:

<body>
   <script>
    var ping = {};
    ping.test = '1234';
   </script>

<a href="#" onclick="alert(ping.test);">Test</a>
</body>

Edit: this works for me

<body>
   <script>
    var ping = {};
    ping.test = '1234';

    function test(){
        alert(ping.test);
    }
   </script>
<a href="#" onclick="test();">Test</a>
</body>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜