简体   繁体   English

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

[英]How to create unique id for each html elements inside a for loop in ejs template?

$(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>
<% } %>

I have multiple show button along with its associated HTML element inside my for loop. 我的for循环中有多个显示按钮及其关联的HTML元素。 I am having a problem in creating unique id s for each HTML element. 我在为每个HTML元素创建唯一id时遇到问题。 As for now, on clicking any of the show buttons the functionality is applied on all of the other HTML elements rather than being applied only on its associated elements. 就目前而言,单击任何显示按钮后,该功能将应用于所有其他HTML元素,而不是仅应用于其关联的元素。 Also I have an unique _id attribute of ans ie ans._id but I don't know to make use of it to create a unique id for my HTML tag from that and how to use that unique id inside my jQuery function. 我也有ans的唯一_id属性,即ans._id但我不知道如何使用它为HTML标签创建唯一的ID,以及如何在jQuery函数中使用该唯一的ID。

No need for IDs 不需要ID

$(document).ready(function() {
  $('.hiddentext').hide(); // can be done in CSS
  $(".show").click(function() {
    $(this).prevAll('.currenttext').hide();
    $(this).prevAll('.hiddentext').show();
    // or $(this).siblings().toggle() as suggested in other post
  });
});
<% for (var ans of quest.answers) { %>
  <div>
    <div class="currenttext"> <%= ans.text %> </div>
    <div class="hiddentext"> <%= ans.description %> </div>
    <a class="show" class="show btn btn-sm btn-primary">show</a>
  </div>
<% } %>

Hide the hidden ones with css so they are immediately hidden on page load. 用css隐藏隐藏的对象,以便在页面加载时立即隐藏它们。

Wrap each group in a container and uses classes and traverses 将每个组包装在容器中并使用类和遍历

 $('.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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM