简体   繁体   English

Javascript为什么标头脚本中的对象属性可以但在html中未定义?

[英]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. 第一个警报在加载时正确显示为“ hello”,但是当我单击按钮时,警报将为完全相同的属性显示“未定义”。

Tested on firefox quantum, from uwamp and directly from file, tried on IE and edge. 从uwamp和直接从文件对Firefox量子进行了测试,并在IE和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. 我想我应该在单击按钮时显示“ Hello”。 Thanks for your help. 谢谢你的帮助。

The problem is that lang is an attribute on the current element: 问题是lang是当前元素的属性:

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

If you do onclick="console.log(lang)" , you'll see it to be an empty string. 如果执行onclick="console.log(lang)" ,则会看到它是一个空字符串。 Either explicitly define lang in the window scope, or use another variable name such as _lang : 在窗口范围内显式定义lang,或使用另一个变量名,例如_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. 请参阅此jsfiddle进行演示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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