【问题标题】:EJS For loop and If statement are not displaying the right valueEJS For 循环和 If 语句未显示正确的值
【发布时间】:2021-03-18 04:42:11
【问题描述】:

我正在构建一个允许用户单击按钮的应用程序,当他们返回页面时,它会显示一条消息“已经感兴趣”。当我显示页面时,它会跳过 for 循环中的 if 语句并显示 else 语句。我做错了什么?

下面是我的代码和当前输出。

<% for(var i=0; i < userInterests.length; i++) { %>
   <% if ((username == userInterests[i].username)  && (postID == userInterests[i].post_id)){ %> 
      <p>Already interested</p>
      <% break; %> 
   <% } else { %> 
      <form action="/jobs/interested/<%= post._id %>" method='POST'>
         <button type="submit" class="btn btn-info">I'm interested</button>
      </form>
      <% break; %> 
   <% } %> 
<% } %>

current output

MongoDB entry

【问题讨论】:

  • 它不喜欢 EJS 的问题。否则,它不会编译。尝试记录if 语句中的所有值并在循环中查看它们的值。这将使您清楚地了解为什么您的 if 语句被评估为错误。
  • 为了让您的逻辑在 js 中更加稳固,请考虑使用 === 而不是 ==
  • 我已经记录了它们的值并且它们与数据库中的条目相匹配。我的代码逻辑有问题吗?

标签: javascript node.js mongodb ejs


【解决方案1】:

逻辑问题,您仅使用 userInterests[0].username 和 serInterests[0].post_id 的值测试用户名和 postID,因为您有中断;在您的 2 个条件中声明,这是该问题的解决方案:

<% var userInterested = false %> 
<% for(var i=0; i < userInterests.length; i++) { %>
   <% if ((username == userInterests[i].username)  && (postID == userInterests[i].post_id)){ %> 
          <% userInterested = true; %>
          <% break; %> 
   <% } %>
<% } %>
<% if (userInterested) { %> 
   <p>Already interested</p>
<% } else { %> 
   <form action="/jobs/interested/<%= post._id %>" method='POST'>
      <button type="submit" class="btn btn-info">I'm interested</button>
   </form>
<% } %>

【讨论】:

    猜你喜欢
    • 2015-04-21
    • 2013-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多