我正在将 todo 对象的数组 todolist 传递到我的 .ejs 文件。此类对象的键是:Action/Date/Priority
我打印出这些键值,如果优先级>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 样式表冲突? 另外,我无法在我的控制台中看到“我在”,我不明白为什么...... 如果有人可以帮助我,谢谢
最佳答案
您的代码中存在语法错误: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>
的第一个字符进行比较的要求。的内容而不是整个字符串。
关于javascript - 如果值修改颜色文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47420985/