[英]Modify colour text if value
我正在向我的.ejs文件传递todo对象的数组todolist 。 此类对象的键为:操作/日期/优先级
我打印出这些键的值,如果优先级> 3,则优先级文本以红色打印;如果优先级== 3,则优先级橙色;如果优先级<= 2,则优先级绿色。 如果不清楚的话,那么看一下代码就会更加清楚。
这是我的代码的相关部分:
<ul id= "list1">
<% todolist.forEach(function(todo, index) { %>
<li><a href="/todo/supprimer/<%= index %>">✘</a>
<%= todo.action %> <%=todo.date%> (priorité: <div id="prio<%index%>"><%=todo.priority%>/5)</div>
</li>
<% }); %>
</ul>
<script>
$('#list1 div').each(function() {
if ($(this).text() <= 2) $(this).css('color', 'green');
if ($(this).text() == 3 ) $(this).css('color', 'orange');
else (this).css('color', 'green');
console.log("i'm in");
});
</script>
我的函数是否可能与外部CSS样式表冲突? 另外,我无法在控制台中看到“我在”,我也不明白为什么...如果有人可以帮助我,谢谢
使用CSS类代替Javascript
.red {
color: red;
}
.green {
color: green;
}
.orange {
color: orange;
}
然后在循环中,检查priority的值
<ul id= "list1">
<% todolist.forEach(function(todo, index) { %>
<li><a href="/todo/supprimer/<%= index %>">✘</a>
<%= todo.action %> <%=todo.date%> (priorité:
<% if (todo.priority <= 2) { %>
<div id="prio<%index%>" class="green"><%=todo.priority%>/5)</div>
<% } else if (todo.priority == 3) { %>
<div id="prio<%index%>" class="orange"><%=todo.priority%>/5)</div>
<% } else if (todo.priority > 3) { %>
<div id="prio<%index%>" class="red"><%=todo.priority%>/5)</div>
<% } %>
</li>
<% }); %>
</ul>
您的代码中存在语法错误: else (this).css
应该是else $(this).css
。 另外,您的if / else条件是不可靠的。 您有if / if / else,但是我想您可能想要if / elseif / else。 我已经更正了这些事情:
$('#list1 div').each(function() {
var priority = $(this).text().substr(0,1);
if (priority <= 2) $(this).css('color', 'green');
else if (priority == 3 ) $(this).css('color', 'orange');
else $(this).css('color', 'red');
});
编辑:我已经更新了答案,以满足与每个<div>
内容的第一个字符而不是整个字符串进行比较的要求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.