javascript - 在客户端 js 文件中使用 pug 变量
问题描述
我能够从节点 js 接收变量到 pug,当我在内联脚本中对其进行控制台时,我能够打印数据。但是如何将变量传递给 pug 文件中包含的外部客户端 js 文件
节点js:
res.render(home, {
title: "home page",
userId: id
})
哈巴狗:
body
-var newId = userId;
script.
var jsNewId = #{newId}
console.log("jsNewId",jsNewId)
此 console.log 打印预期的 newid 值。我想将相同的值发送到 pug 文件页脚中包含的 js 文件:
script(src="js/client.js type="text/javascript)
客户端.js
$(document).ready(function () {
var jsNewId = #{newId} //cannot use this syntax
})
如何在客户端 js 文件中获取 pug 变量
解决方案
为了使用script
在外部 javascript 文件中的内联标记中声明的 javascript 变量,您需要将其设为全局变量(不推荐),或使用类似local storage的东西:
在您的 Pug 文件中(请务必在 中缩进您的script
标签body
)
body
- let newId = userId
script.
let jsNewId = #{newId}
localStorage.setItem('jsNewId', jsNewId)
然后在你的 client.js 文件中:
$(document).ready(function () {
let jsNewId = localStorage.getItem('jsNewId')
})
最好将您的 client.js 文件作为最后一项包含在 中,body
以确保jsNewId
在尝试获取它之前存在于本地存储中。
推荐阅读
- python - 给定有效负载的 .jpg 文件验证 UDP 的 CRC32
- c# - 我的检查和购买对象说:并非所有代码路径都返回一个值
- java - 异常(stacktrace)在 springboot 单元测试中不可用
- python - 仅使用 dlib 对 iPhone 照片进行面部检测失败
- c++ - 如何在红黑树中重载 operator=?C++
- python - 用 Python bs4 从 HTML 中提取文本
- azure-functions - 如何仅使用逻辑应用 HTTP 操作将 HTTP 触发 azure 函数连接到我的 azure 逻辑应用?
- python - 展示 pandas DataFrame 进化
- firebase - Firestore 错误:流以状态关闭:PERMISSION_DENIED
- java - Android - 不推荐使用 getExternalStorageDirectory() 后获取 SD 卡路径位置