简体   繁体   English

jquery 字体颜色脚本基于值包含

[英]jquery font color script based on value contains

I have a simple if else statement that will color a number based on it's value.我有一个简单的 if else 语句,它将根据它的值为数字着色。

Can anyone explain why the below always results in red?谁能解释为什么下面总是导致红色?

 $(document).ready(function() { // the following will select all elements with class "deltadiff" // if the element has a '-', it will assign a 'red' class, else it will assign the 'green class' if ($(".deltadiff:contains('-')")) $(".deltadiff").addClass('red'); else $(".deltadiff").addClass('green'); } )
 .red { color: red; }.green { color: green; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <font class="deltadiff" style="font-size:10px; vertical-align:super;"> -120</font> <font class="deltadiff" style="font-size:10px; vertical-align:super;"> 120</font> <font class="deltadiff" style="font-size:10px; vertical-align:super;"> 5</font> <font class="deltadiff" style="font-size:10px; vertical-align:super;"> -7</font>

if ($(".deltadiff:contains('-')")) only checks for the first element that has deltadiff as classname. if ($(".deltadiff:contains('-')"))仅检查以deltadiff作为类名的第一个元素。

You should loop through all the elements with the same class .您应该遍历所有具有相同 class 的元素

Then, use includes() to check if the innerHTML contains an - .然后,使用includes()检查innerHTML是否包含-

 $(document).ready(function() { // For each element with class: 'deltadiff' $('.deltadiff').each(function(i, obj) { // if the element has a '-', it will assign a 'red' class, else it will assign the 'green class' if (obj.innerHTML.includes('-')) { obj.classList.add("red"); } else { obj.classList.add("green"); } }); });
 .red { color: red; }.green { color: green; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <font class="deltadiff" style="font-size:10px; vertical-align:super;"> -120</font> <font class="deltadiff" style="font-size:10px; vertical-align:super;"> 120</font> <font class="deltadiff" style="font-size:10px; vertical-align:super;"> 5</font> <font class="deltadiff" style="font-size:10px; vertical-align:super;"> -7</font>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM