一旦我通过Node.js作为对象传递数组,我如何控制我的ejs文件中的数据

时间:2017-06-22 17:48:17

标签: javascript node.js express ejs

我正在使用Node.js和ejs创建一个基本的日历应用程序。我试图通过快递向我的ejs传递一个月的数组,我希望每个月都可以通过按下一个按钮。如何添加该功能。

以下是Node.js中的代码。

const Months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
];

正如您所看到的那样,我通过主路线将月份作为对象传递。

// main route
app.get("/", function(req, res){
res.render("main", {Months: Months});
});

这是我的ejs文件的一部分

<div class="container">
 <ul style="margin: 0; padding: 0; list-style-type: none">
<li class="prev" style="float: left; padding-top: 10px; color: white; font-size: 20px; text-transform: uppercase; letter-spacing: 3px;">

<!-- this is the previous button, when pressed should go back one month -->
<button class="btn btn-default" type="submit">Previous</button></li>

<li class="next" style="text-align: right; padding-top: 10px; color: white; font-size: 20px; text-transform: uppercase; letter-spacing: 3px;">

<!-- This is the next button, when pressed should go on the next month  -->
<button class="btn btn-default" type="submit">Next</button></li>

<li style="color: white; font-size: 20px; text-transform: uppercase; letter-spacing: 3px; text-align: center;">

这是我传递Month对象的地方。我如何在这里控制数据,所以当我按下Next或Previous按钮时,我可以遍历数据。

<%= Months[0] %><br>
  <span style="font-size:18px">2016</span>
</li>
 </ul>

1 个答案:

答案 0 :(得分:0)

该值仅在服务器端可用。如果您对该值进行解码,则可以在客户端使用它。

这是一个简单的例子。

<p id="month"></p>
<p>
<button id="prev">prev</button>
<button id="next">next</button>
</p>
<script>
let months = <%- JSON.stringify(Months) %>;

let index = 0;

let el = document.getElementById('month');

document.getElementById('prev').addEventListener('click', e => {
index--;

index = index < 0 ? 0 : index;

el.innerHTML = months[index];
});

document.getElementById('next').addEventListener('click', e => {
index++;

index = index >= months.length ? months.length - 1 : index;

el.innerHTML = months[index];
});
</script>