gpt4 book ai didi

javascript - 如何在ejs模板中的for循环内为每个html元素创建唯一的id?

转载 作者:行者123 更新时间:2023-12-01 03:22:42 25 4
gpt4 key购买 nike

$(document).ready(function() {
$('#hiddentext').hide();

$("#show").click(function() {
$('#currenttext').hide();
$('#hiddentext').show();
});
});
<% for (var ans of quest.answers) { %>
<div id="currenttext"><%= ans.text %></div>
<div id="hiddentext"><%= ans.description %></div>
<a id="show" class="btn btn-sm btn-primary">show</a>
<% } %>

我的 for 循环中有多个显示按钮及其关联的 HTML 元素。我在为每个 HTML 元素创建唯一的 id 时遇到问题。就目前而言,单击任何显示按钮时,该功能将应用于所有其他 HTML 元素,而不是仅应用于其关联元素。另外,我有一个 ans 的唯一 _id 属性,即 ans._id 但我不知道如何利用它来创建唯一的 id从中了解我的 HTML 标记以及如何在我的 jQuery 函数中使用该唯一 id。

最佳答案

使用 css 隐藏隐藏的内容,以便它们在页面加载时立即隐藏。

将每个组包装在容器中并使用类和遍历

$('.show').click(function() {
$(this).siblings().toggle();
})
.hiddentext {
display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class="currenttext">Answer #1</div>
<div class="hiddentext">Descrip #1</div>
<a class="show btn btn-sm btn-primary">Show</a>
</div>
<div>
<div class="currenttext">Answer #2</div>
<div class="hiddentext">Descrip #2</div>
<a class="show btn btn-sm btn-primary">Show</a>
</div>
<div>
<div class="currenttext">Answer #3</div>
<div class="hiddentext">Descrip #3</div>
<a class="show btn btn-sm btn-primary">Show</a>
</div>

关于javascript - 如何在ejs模板中的for循环内为每个html元素创建唯一的id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45063251/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com