最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Give style following If condition in EJS - Stack Overflow

programmeradmin2浏览0评论
<% docs.forEach( function ( doc ){ %>

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

<% }); %>

Imagine 3 docs,

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

I want to give style to Active == true only. I coded like above, but the result is every div was given style. so finally all has red background, this is not what I expected.

How can I give style conditionally in EJS?

<% docs.forEach( function ( doc ){ %>

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

<% }); %>

Imagine 3 docs,

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

I want to give style to Active == true only. I coded like above, but the result is every div was given style. so finally all has red background, this is not what I expected.

How can I give style conditionally in EJS?

Share Improve this question edited Jan 2, 2016 at 6:19 ton1 asked Jan 2, 2016 at 6:07 ton1ton1 7,62822 gold badges80 silver badges129 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

You would want to conditionally set a class like .active and have that with your CSS styles (such as the red background-color). Like this:

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

The syntax is:

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

and to only set that to just one of the items, use:

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

<% docs.forEach( function ( doc ){ %>

<% if (doc.Active) { %>
   <div class="item acitve">
<% } else { %>
   <div class="item">
<% } %>

   ...

  </div>

<% }); %>
发布评论

评论列表(0)

  1. 暂无评论