簡體   English   中英

如何在ejs中向HTML元素添加自定義樣式?

[英]How to add custom style to a HTML element in ejs?

我正在創建一個Bug跟蹤系統作為學習Node.js的項目。 我遇到的問題是,我想相對於狀態值更改表格行(在下面的屏幕截圖中)背景色(例如對於OPEN,我希望顏色為紅色,對於閉合為綠色,等等)。

<table class="table">
    <thead>
        <tr>
            <th>Project</th>
            <th>Status</th>
            <th>Date Created</th>
            <th>Bug</th>
            <!--  -->
            <th>Description</th>
            <th>Date Solved</th>

        </tr>
    </thead>     
    <tbody>
        <% bugs.forEach(function(bugs){ %>
        <tr id ="color">
            <td><a style="text-decoration:none" href="/"><%= bugs.projectName%></a></td>
            <td><%= bugs.status %> 
                <% if (bugs.status === "OPEN") { %>
                <% document.getElementById("color").style.color = "green"; %>
                <% } %>                         
            </td>
            <td><%= bugs.dateCreated %></td>
            <td><a style="text-decoration:none; color : #000;" href="/bugs/<%= bugs._id %>"><%= bugs.title %></a></td>
            <td><a style="text-decoration:none; color : #000;" href="/bugs/<%= bugs._id %>"><%= (bugs.description).substr(0, 40) %></a></td>
            <td><%= bugs.dateSolved %></td>
        </tr>  
        <% }); %>
    </tbody>
</table>

產生的錯誤:

錯誤

您的<tr>不應具有id因為它可能會在頁面上重復多次。 我相信在這里class會更合適。 有關ID和類之間的區別的更多信息,請參見https://css-tricks.com/the-difference-between-id-and-class/

我認為添加到您的<tr>類似內容可能會解決問題。

<tr style="<%= bugs.status === 'OPEN' ? 'color: green' : '' %>">

要記住的一件事; 大多數人都像我的例子一樣看不起內聯樣式。 更好的選擇是制作一個樣式類,使其具有“開放”行所需的所有樣式,然后使用類似我上面顯示的三元數來應用該類。

// somewhere in your stylesheet
.open-bug { color: green; }
<tr class="<%= bugs.status === 'OPEN' ? 'open-bug' : '' %>">

EJS是在服務器上呈現的,而不是在瀏覽器上呈現的,因此EJS不知道是什么document ,因為那是僅在瀏覽器中定義的document

您可以通過使用類似於Dan在上面的回答中所做的內聯樣式的方式來解決您的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM