【问题标题】:How to get a MySQL Value as a colour in EJS?如何在 EJS 中获取 MySQL 值作为颜色?
【发布时间】:2019-10-07 20:51:02
【问题描述】:

我的 nodeJS 项目中有一个表,其中包含带有状态的数据。我想用红色和绿色显示这个状态。为了呈现 HTML 页面,我使用 EJS。

我已经尝试过使用 if/else 语句,但我总是得到语句的第一个值。

MySQL:

SELECT g_id, g_name, g_status FROM games

EJS:

<table class="table table-hover">
            <thead>
                <tr class="table-info">
                    <th>Name</th>
                    <th>Status</th>
                </tr>
            </thead>

        <% if (data) { 
            data.forEach(function(game){ 

            var status = game.g_status;

            if (status = '1') {
                status = 'color-green';
            } else {
                status = 'color-red';
            }
        %>
        <tbody id="myTable">
            <tr>
                <td><%= game.g_name %></td>
                <td><%= status %></td>
            </tr>
        </tbody>
        <% }) %>
        <% } %>
</table>

出了什么问题,如何将 SQL 输出转换为特定颜色?

【问题讨论】:

  • 不应该是:if (status == '1') { ?
  • 是的,没错,我可能忽略了

标签: javascript html mysql node.js ejs


【解决方案1】:

像这样使用三元条件:

<table class="table table-hover">
            <thead>
                <tr class="table-info">
                    <th>Name</th>
                    <th>Status</th>
                </tr>
            </thead>

        <% if (data) { 
            data.forEach(function(game){ %>
            <tbody id="myTable">
            <tr>
                <td><%= game.g_name %></td>
                <td><%= game.g_status=='1'?'color-green':'color-red' %></td>
            </tr>
            </tbody>
        <% }) %>
        <% } %>

【讨论】:

  • 这很好用,但是如何将两个值都输出为颜色?
  • 这取决于你的要求,当你想显示两种颜色时
  • 如果DB中的status设置为1,这些值如果绿色为2,则这些值应该显示为红色。
  • 我只是尝试通过 JS 变量来执行此操作,但我没有得到任何 HTML 样式
  • 在你的 if 条件下尝试 double = , ` if (status == '1') {`
【解决方案2】:

好吧。 有很多地方要找。

  1. 阅读 JavaScript 中的等号运算符
  2. 状态不是列表的一部分,只是应用变量
  3. 为给定状态创建返回颜色的函数

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-26
    • 1970-01-01
    • 1970-01-01
    • 2019-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多