在EJS / node.js中的forEach中使用“this”项添加一个css类
我一直在尝试这个小时,但我很难过。
我有一种“购物清单”node.js应用程序,您可以勾选bought
物品。 我想要购买的物品是绿色或水货样式。 它沿着一条路线传递一个mongooseobj到客户端。
服务器端:
router.get("/:id", function(req, res){ //find the list with provided ID List.findById(req.params.id).populate("listItems").exec(function(err, foundList){ if(err){ console.log(err); } else { //render show template with that list res.render("lists/show", {list: foundList});
foundList
obj基本上有一个(不是有效的代码,只要你能得到一个想法)的结构:
List { name: String, listItems: [{ text: String, bought: Boolean }]
在客户端,我在ejs中使用forEach来遍历listItems,并为每个项目显示一个html元素:
<% list.listItems.forEach(function(listItem){ %> <div class="card"> <div class="card list"> ..listItem name here </div> </div> <% }) %>
我想基本上这样做,当一个元素被closures和listItem.bought == true
, card list
元素是绿色的,当lisItem.bought == false
,它只是白色。
我已经得到它与以下代码工作,但是,如果forEach的一个出现bought = true
,所有.card
元素变成绿色。 我想要它只有这个元素是有效的。
<% list.listItems.forEach(function(listItem){ %> <% if(listItem.bought === true){ %> <script> $(document).ready(function(){ (".card").css("background-color","green"); }); </script> <% } else { %> <script> $(document).ready(function(){ (".card").css("background-color","white"); }); </script> <% } %> <div class="card"> <div class="card list"> ....
问题:如何从ejs中的服务器端数据定位1次forEach,并为其添加类/样式。 例如,如果列表中有2个项目,则购买1个,而不是1个应该是绿色和白色。 目前他们都走绿色。
谢谢!
我不认为你需要这个jQuery。 你可以像这样添加背景颜色:
<% list.listItems.forEach(function (listItem) { %> <div class="card" style="background-color: <%= listItem.bought ? 'green' : 'white' %>"> <div class="card list"> ... </div> </div> <% }); %>
如果你想使用jQuery,你可能需要添加ID到卡上,并使用它们来改变背景。