[英]How do I replace text in an EJS template on hovering with a variable sent from a node js controller?
I have the following code snippet in my EJS file (as part of a node application).我的 EJS 文件中有以下代码片段(作为节点应用程序的一部分)。
<% for(var i = 0; i < documents.length; i++) { %>
<li><%= documents[i] %></li>
<h4 hidden> <%= my_dict[documents[i]] %></h4>
<% } %>
<script>
$('li').hover(
function () {
const doc_text = $('.plain').text()
const doc_mapping = my_dict[doc_text]
$(this).replaceWith(doc_mapping);
}
);
</script>
Here, my_dict
is a dictionary and documents
is an Array which is passed from my node js controller在这里,
my_dict
是一个字典, documents
是一个从我的节点 js 控制器传递的数组
I basically need to replace the text of each <li>
tag in the loop with the text my_dict[text]
on hovering.我基本上需要在悬停时用文本
my_dict[text]
循环中每个<li>
标签的文本。 I tried to do so using the above script but it isn't working.我尝试使用上面的脚本这样做,但它不起作用。 I also tried to include the text in a
<h4>
tag which is kept hidden and use it to replace the text.我还尝试将文本包含在保持隐藏的
<h4>
标签中,并用它来替换文本。
But every time I hover over the text in the <li>
tag, it gets replaced by all the text in all the tags of the loop.但是每次我将鼠标悬停在
<li>
标签中的文本上时,它都会被循环的所有标签中的所有文本替换。 Probably because I am not able to map each <li>
uniquely to each <h4>
tag.可能是因为我无法将每个
<li>
唯一地映射到每个<h4>
标签。
Any help is really appreciated.任何帮助都非常感谢。
If i understand well your problem, here is a simple solution.如果我很了解您的问题,这里有一个简单的解决方案。
<% for(var i = 0; i < documents.length; i++) { %>
<li onmouseenter="hover(this, '<%= my_dict[documents[i]] %>')" onmouseleave="hover(this, '<%= documents[i] %>')"><%= documents[i] %></li>
<h4 hidden> <%= my_dict[documents[i]] %></h4>
<% } %>
<script>
function hover(el, str) {
el.innerHTML = str;
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.