我在我的应用程序中使用节点 js 和 ejs 模板,我试图在搜索字段不匹配任何结果的情况下显示一条消息,我希望它会显示“行不存在。”,但它显示搜索结果,如下面的屏幕截图所示:
我尝试以不同的方式修改if语句
<% } else if(oneresult != ''){ %>
中的条件,但它不起作用。下面是代码:
<%- include('partials/header') -%>
<div class="container mt-5 w-50">
<h2 class="mb-4">Search a Line</h2>
<form action="/line" method="GET">
<input
type="text"
name="line"
class="form-control"
placeholder="Enter a Line"
/>
<button type="submit" class="btn btn-danger btn-block mt-3">
Search in Database
</button>
</form>
<% if(oneresult) { %>
<h4 class="text-danger my-4">Search Results:</h4>
<table class="table table-bordered" width="100%" cellspacing="0">
<thead>
<tr>
<th>ID</th>
<th>Line</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<% oneresult.forEach( oneresult=>{ %>
<tr>
<td><%= oneresult.id %></td>
<td><%= oneresult.result %></td>
<td><%= oneresult.date %></td>
</tr>
<% }) %>
</tbody>
</table>
<% } else if(oneresult != ''){ %>
<div class="alert alert-danger mt-4">Line does not exist.</div>
<% } %>
</div>
<%- include('partials/footer') -%>
有什么建议吗?
根据您提供的代码,看起来
oneresult
变量在某些情况下可能为空或未定义。一种确保消息“线路不存在”的方法。仅在没有搜索结果时出现,是为了在显示搜索结果表之前检查oneresult
是否定义且不为空。这是带有此检查的代码的更新版本:
<%- include('partials/header') -%>
<div class="container mt-5 w-50">
<h2 class="mb-4">Search a Line</h2>
<form action="/line" method="GET">
<input
type="text"
name="line"
class="form-control"
placeholder="Enter a Line"
/>
<button type="submit" class="btn btn-danger btn-block mt-3">
Search in Database
</button>
</form>
<% if (oneresult && oneresult.length > 0) { %>
<h4 class="text-danger my-4">Search Results:</h4>
<table class="table table-bordered" width="100%" cellspacing="0">
<thead>
<tr>
<th>ID</th>
<th>Line</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<% oneresult.forEach(oneresult => { %>
<tr>
<td><%= oneresult.id %></td>
<td><%= oneresult.result %></td>
<td><%= oneresult.date %></td>
</tr>
<% }) %>
</tbody>
</table>
<% } else if (oneresult !== undefined && oneresult.length === 0) { %>
<div class="alert alert-danger mt-4">Line does not exist.</div>
<% } %>
</div>
<%- include('partials/footer') -%>
在此更新版本中,消息“线路不存在”。只有在定义了
oneresult
并且是一个空数组时才会出现。如果 oneresult
未定义或根本未定义,则不会出现该消息。
我找到了解决这个问题的方法。在第一个 if 语句中,我写了以下条件
if(Object.keys(oneresult).length > 0)
因为猫鼬 find() 返回一个对象所以我检查它是否大于 0 并且在 else 块中我写了 <% } else if(oneresult !== ""){ %>
.