[英]How to pass an ejs variable to javascript?
I cannot transfer ejs variable to javascript. 我无法将ejs变量传输到javascript。 I have a for in ejs:
我在ejs中有一个for:
<% for(var i=0; i < lyrics.length; i++) {%>
<!--MELODIE-->
<br>
<%= lyrics[i].texte %>
and I want to log in browser lyrics[i].texte variable. 我想登录浏览器lyrics [i] .texte变量。 I tried
var a = <%= lyrics[i].texte %>;
我尝试了
var a = <%= lyrics[i].texte %>;
but it didn't worked. 但是没有用。 I also tried to to set in ejs
<% v1= lyrics[i].texte ; %>
我还尝试在ejs中设置
<% v1= lyrics[i].texte ; %>
<% v1= lyrics[i].texte ; %>
and to set js var equal to v1 but it didn't worked again. <% v1= lyrics[i].texte ; %>
并将js var设置为等于v1,但此操作再次失败。 I have to convert lyrics[i].texte into a js variable. 我必须将lyrics [i] .texte转换为js变量。
I think that the problems came from .texte after name of var (texte is the name of column in database and it's a string). 我认为问题来自var名称后的.texte(texte是数据库中列的名称,它是一个字符串)。 I store in it a poesy.
我在其中储存一首诗。 And when i use a standard var (like <%var = 30%>) it runs ok in js transfer.
当我使用标准var(如<%var = 30%>)时,它在js传输中运行正常。 Thanks for the help!
谢谢您的帮助!
First you have to stringify your var because is an array. 首先,您必须将var字符串化,因为它是一个数组。 Use
var myVar = <%-JSON.stringify(ejsVar)%>;
使用
var myVar = <%-JSON.stringify(ejsVar)%>;
to fix your problem. 解决您的问题。
Now you can use myVar in javascript. 现在您可以在JavaScript中使用myVar。
<% lyrics.forEach(lyric=> { %>
<li class="<%=lyric.texte %>"><%=lyric.texte %></li>
<% }); %>
here is the code for looping lyrics
, if you want to access a specific lyric.texte
, you have to make document.querySelector(".className");
这是循环
lyrics
的代码,如果要访问特定的lyric.texte
,则必须制作document.querySelector(".className");
in your javascript file. 在您的javascript文件中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.