简体   繁体   中英

Javascript why is object property ok in header script but undefined in html?

The first alert displays correctly "hello" at load time, but when I click on the button, the alert displays "undefined" for exactly the same property.

Tested on firefox quantum, from uwamp and directly from file, tried on IE and edge.

<html>
    <head>
        <meta charset="UTF-8"/>
        <title>TestObjectProperty</title>
            <script type="text/javascript"> 

                lang = {
                    greeting: "Hello",
                    bye: "good bye!"
                };

                alert(lang.greeting); 
                //works fine, alert shows Hello

            </script>
    </head>
    <body >
        <button  onclick="alert(lang.greeting);">test lang</button>
        <!-- alert shows UNDEFINED -->
    </body>
</html>

I guess I should have "Hello" showing up when the button is clicked. Thanks for your help.

The problem is that lang is an attribute on the current element:

https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/lang

If you do onclick="console.log(lang)" , you'll see it to be an empty string. Either explicitly define lang in the window scope, or use another variable name such as _lang :

<html>
    <head>
        <meta charset="UTF-8"/>
        <title>TestObjectProperty</title>
            <script type="text/javascript"> 

                window.lang = {
                    greeting: "Hello",
                    bye: "good bye!"
                };

                alert(window.lang.greeting); 
                //works fine, alert shows Hello

            </script>
    </head>
    <body >
        <button  onclick="alert(window.lang.greeting);">test lang</button>
        <!-- alert should show "Hello" -->
    </body>
</html>

See this jsfiddle for a demonstration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM