我正在使用 jQuery 将一些 html 附加到 div
:
public/js/writeInputs.js
$("#myDiv").append("<input type='search' value='<%= filters.title %>' name='filters[title]' class='form-control'>")
在这种情况下,filters
是我从我的 node express 后端传递的一个对象,我想在我的输入中显示它的值。但是,上面将 ejs
变量呈现为字符串文字:
<%= filters.title %>
如果我将这个值硬编码到 html 中,它会按预期工作:
views/partials/inputs.ejs
<input type="search" name="filters[title]" value="<%= filters.title %>" class="form-control">
如何在 jQuery 中编写 ejs 变量?
我在我的附录中尝试了这些方法,但都没有用:
value="<%= filters.title %>"
value=${<%= filters.title %>}
value='"<%= filters.title %>"'
最佳答案
Node Express 首先呈现 HTML,然后浏览器基于 HTML 进行一些请求以获取脚本、图像等。因此 <%= filters.title %>
不被 EJS 解释。
作为替代方案,将一些数据呈现为 HTML 并重写 JavaScript 以读取 filters.title
来自 HTML,像这样:
<input type="hidden" id="filter" value="<%= filters.title %>" />
<script src="yourScript.js"></script>
yourScript.js:
var filter = document.getElementById("filter").value;
$("#myDiv").append("<input type='search' value='" + filter + "' name='filters[title]' class='form-control'>");
关于javascript - 在 jQuery 中写入 ejs 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56548995/