我做了一个hbs页面(dashboard),它由app.js渲染,在渲染//res.render('dashboard',{user:user})
时传递了一个'user' name变量。我可以很容易地在hbs文件中使用for每个循环并成功地显示其内容,但是当我试图通过脚本文件访问变量时,当我在console.log中传递它时,它在开发者控制台中显示为undefined。请帮助我与json一样的助手,我尝试了它,但给出错误。
dashboard.hbs:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Dashboard</title>
<link rel="stylesheet" href="styles.css">
{{>navbar name=name logout=logout}}
<style>
*{
font-family: 'Poppins',sans-serif;
box-sizing: border-box;
}
h1{
position: relative;
top:20px;
text-align: center;
font-size: 40px;
color: white;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
</head>
<body>
<div class="search-bar">
<input type="text" id="input" placeholder="Add task...">
<button type="submit" id="add">Add</button>
</div>
<div class="container">
<div id="left" class="faded"><h1> Tasks <img src="task.png" width="50" height="45"></h1>
{{#each user.dashboard}}
<div class="list" draggable="true"><img class="bulletin" src="bulletin.png"/>{{this.tasks}}<img class="delete" id="delete" src="delete.png"/></div>{{/each}}
</div>
<div id="middle" class="faded"><h1>In Progress <img src="progress.png" width="50" height="45"></h1></div>
<div id="right" class="faded"><h1>Completed <img src="completed.png" width="50" height="45"></h1></div>
</div>
<script> var user =`{{ user}}`;</script>
<script src="script.js"></script>
</body>
</html>
script.js:
$(document).ready(function () {
console.log(user.username);
$("#add").on("click", function () {
if ($("#input").val() != '') {
var div = $("<div>").addClass("list").attr("draggable", true);
var img = $('<img />', {
class: 'bulletin',
src: 'bulletin.png',
});
div.append(img);
div.append($("#input").val());
var del = $('<img />', {
class: 'delete',
src: 'delete.png',
id: 'delete',
});
div.append(del);
$("#left").append(div);
dragAndDrop();
}
});
$(document).on('click', '.delete', function (e) {
$(this).closest('div').remove();
});
dragAndDrop();
function dragAndDrop() {
$(".list").on("dragstart", function (e) {
let selected = $(this);
$("#left, #middle, #right").on("dragover", function (e) {
e.preventDefault();
});
$("#left, #middle, #right").on("drop", function (e) {
$(this).append(selected);
selected = null;
});
});
}
});
{
username: {
type:String,
required: true
},
email:{
type:String,
required:true,
unique:true
},
password:{
type:String,
required:true,
unique:true
},
confirmpassword:{
type:String,
required:true,
unique:true
},
phone:{
type:Number,
required: true,
unique: true
},
age:{
type:Number,
required:true,
},
tokens:[{
token:{
type: String,
required:true,
}
}],
dashboard:[{
tasks:{
type:String,
default: 0
},
}]
}
对不起的细节,如果我做了
1条答案
按热度按时间dw1jzc5e1#
Handlebars在服务器上运行,而脚本在浏览器中运行-这就是为什么您不能从脚本访问
user
变量的原因之一。一种可能性是在脚本标记中序列化变量。
首先,你需要注册一个助手,比如:
现在在你的脚本文件中:
记住去掉敏感信息,比如
password
(顺便说一下,它不应该是唯一的,也不应该存储为纯文本!)).