如何从位于同一文件中的 JS 脚本更新 EJS 中的变量?
如标题中所述,我在 ejs 部分的 scriplet 标签中有这个变量“i”:
<span class="UTXOindex"><% var i = 0 %></span>
<div class="test"></div>
并且我在同一文件的 JS 脚本部分中有以下内容,希望能够增加上述变量:
<script>
document.getElementById("nextButton").addEventListener("click", e => {
e.preventDefault()
document.querySelector(".test").insertAdjacentHTML(
"afterbegin",
`
<p>The number was <%= i %></p>
<% i++ %>
<p>The number is now <%= i %></p>
`
)
})
</script>
我是尝试从 JS 脚本部分更新 ejs 部分中的变量“i”,但多次触发事件侦听器后似乎没有更新。触发 .addEventListener 几次将如下所示:
The number was 0
The number is now 1
The number was 0
The number is now 1
The number was 0
The number is now 1
我希望得到以下输出:
The number was 0
The number is now 1
The number was 1
The number is now 2
The number was 2
The number is now 3
等等......
有什么建议吗?以及如何永久更新 EJS scriplet 标签中的变量?
As stated in the titled, I have this variable 'i' in the scriplet tags of the ejs part:
<span class="UTXOindex"><% var i = 0 %></span>
<div class="test"></div>
and I have the below in the JS script part in the same file with the hopes of being able to increment the above variable:
<script>
document.getElementById("nextButton").addEventListener("click", e => {
e.preventDefault()
document.querySelector(".test").insertAdjacentHTML(
"afterbegin",
`
<p>The number was <%= i %></p>
<% i++ %>
<p>The number is now <%= i %></p>
`
)
})
</script>
I am trying to update the variable 'i' in the ejs part from the JS script part but it doesn't seem to update after triggering the event listener multiple times. Triggering the .addEventListener a few times would look like the below:
The number was 0
The number is now 1
The number was 0
The number is now 1
The number was 0
The number is now 1
I was hoping for the below output:
The number was 0
The number is now 1
The number was 1
The number is now 2
The number was 2
The number is now 3
and so on so forth...
Any suggestions? And how to permanently update a variable in EJS scriplet tags?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 HTML 数据属性。
您还可以像这样分配值:
You can use HTML data attribute.
You can also assign value like this: