从 HTML 头中的变量读取数组值
这是 HTML 结构...
<head>
...
<script>
ENV = {...,
current_user: {
id: "314",
display_name: "My name"
}
}
<script/>
...
<head/>
我正在尝试读取“display_name”以在应用程序的另一部分中使用。
如果我按 F12 并在控制台中运行以下命令,它可以返回名称:
console.log(ENV.current_user.display_name)
但以下命令在上面的同一页面内不起作用:
<script>
const x = ENV.current_user.display_name;
document.getElementById("std").innerHTML = x;
</script>
<h3 id="std"></h3>
如何在这个 h3 中打印“我的名字”?
This is the HTML structure...
<head>
...
<script>
ENV = {...,
current_user: {
id: "314",
display_name: "My name"
}
}
<script/>
...
<head/>
I'm trying to read "display_name" to use in another part of the application.
If I press F12 and run the below in the console it works returning the name:
console.log(ENV.current_user.display_name)
but below doesn't work inside same page of the above:
<script>
const x = ENV.current_user.display_name;
document.getElementById("std").innerHTML = x;
</script>
<h3 id="std"></h3>
How can I print "My name" inside this h3?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您看不到该名称,因为脚本需要移至正文。
JavaScript 正在寻找 div,但它返回 NULL,因为您的 JS 在页面加载之前已被调用。
You're not seeing the name because the script needs to be moved to the body.
JavaScript is looking for the div however it's returning NULL because your JS has be called before the page has been loaded.
您可以在所有页面中导入全局配置文件(config.js),然后包含其他脚本
,您的配置文件将具有 ENV 变量。
由于页面加载时间的原因,不应在标头中声明脚本,始终建议将它们放在 body 标记内的末尾
you can import in all pages a global configuration file (config.js) and then include others scripts
and your config file would have the ENV variable.
the scripts should not be declared in the header for reasons of page load time, it is always recommended to place them at the end inside the body tag
当脚本运行时,您的 std 元素尚未呈现。这应该有效:
将其放入正文中,位于正文的末尾。
Your std element isn't rendered yet when your script is running. This should work:
Put it in the body, at the end of the body.
你的脚本
不起作用,因为你的脚本在 DOM 完成加载之前运行,因此它们将返回 null 或未定义。您可以做的是将您的内容放在
的末尾
这是整个代码的样子:
确保浏览器运行脚本的另一种方法加载 HTML 后,将 js 脚本分离到不同的文件中,并通过
将 其包含在 HTML 中
defer
告诉浏览器仅在加载 HTML 时运行filename.js
。Your
doesn't work because your script run before the DOM finished loading, so they will return null or undefined. What you can do is to put your at the end of
<body></body>
Here is the what the entire code should look like:
Another way to make sure that your browser run the script after HTML is loaded is by separate the js script to different a file and include it in HTML by
<script defer src='./filename.js'></script>
The word
defer
tell the browser to runfilename.js
only when the HTML is loaded.