【问题标题】:Give style following If condition in EJS在 EJS 中根据 If 条件给出样式
【发布时间】:2016-04-06 09:55:09
【问题描述】:
<% docs.forEach( function ( doc ){ %>

<div class="item">
    <% if (doc.Active) { %>
    <style> .item { background-color:red }</style>
    <% } %>
</div>

<% }); %>

想象 3 个文档,

doc1 (Active == true)
doc2 (Active == true)
doc3 (Active == false)

我只想为Active == true 赋予风格。我像上面那样编码,但结果是每个div 都被赋予了样式。所以最后都是红色背景,这不是我所期望的。

如何在 EJS 中有条件地赋予样式?

【问题讨论】:

    标签: javascript css ejs


    【解决方案1】:

    语法是:

    <style> .item { background-color:red; } </style>
    

    如果只将其设置为其中一项,请使用:

    <style>
       .active { background-color:red; } 
    </style>
    
    <% docs.forEach( function ( doc ){ %>
    
    <% if (doc.Active) { %>
       <div class="item acitve">
    <% } else { %>
       <div class="item">
    <% } %>
    
       ...
    
      </div>
    
    <% }); %>
    

    【讨论】:

      【解决方案2】:

      您可能希望有条件地设置一个像 .active 这样的类,并将其与您的 CSS 样式(例如红色背景色)一起使用。像这样:

      <% docs.forEach(function (doc) { %>    
        <div class="item <%= doc.Active ? 'active' : '' %>"></div>
      <% }); %>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-11
        • 2016-08-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多